Get All The Partitions Of The Set Python With Itertools
How to get all partitions of a set? For example, I have array [1, 2, 3]. I need to get [[1], [2], [3]], [[1], [2, 3]], [[2], [1,3]], [[3], [1, 2]], [[1, 2, 3]]. Now, I wrote this
Solution 1:
I wrote this one for fun:
defpartition(a_list):
yield [[x] for x in a_list]
for i inrange(1, len(a_list) + 1):
_l = a_list[:]
yield [_l.pop(i-1), _l]
yield a_list
my_list = [1, 2, 3]
printlist(partition(my_list))
#orfor p in partition(my_list):
print p
Solution 2:
a = [1, 2, 3]
b = list()
for l in range(len(a)+1): b.append([c for c in combinations(a, l)])
print(b)
check this
Post a Comment for "Get All The Partitions Of The Set Python With Itertools"