Reconstruct This Generator To Yield Sorted Nested Tuples Instad Of Nested Lists
I currently have the folliwng generator that yields nested lists (to construt the set of partitions of a set), but i actualy need it to output nested tuples. I currently use a to_t
Solution 1:
Here's what I've got:
def_partition(collection):
# from here: https://stackoverflow.com/questions/19368375/set-partitions-in-python/61141601"
collection = tuple(collection)
iflen(collection) == 1:
yield (collection,)
return
first = collection[0]
for smaller in _partition(collection[1:]):
# insert `first` in each of the subpartition's subsetsfor n, subset inenumerate(smaller):
yieldtuple(sorted(
smaller[:n]
+ (tuple(sorted((first,) + subset)),)
+ smaller[n + 1 :]
))
# put `first` in its own subsetyieldtuple(sorted(((first,),) + smaller))
With
example = [0, 0, 1, 4]
for p in _partition(example):
print(p)
the output would be:
((0, 0, 1, 4),)
((0,), (0, 1, 4))
((0, 0), (1, 4))
((0,), (0, 1, 4))
((0,), (0,), (1, 4))
((0, 0, 1), (4,))
((0, 1), (0, 4))
((0,), (0, 1), (4,))
((0, 0, 4), (1,))
((0, 1), (0, 4))
((0,), (0, 4), (1,))
((0, 0), (1,), (4,))
((0,), (0, 1), (4,))
((0,), (0, 4), (1,))
((0,), (0,), (1,), (4,))
And in unsorted case
example = [2, 0, 1, 4]
for p in _partition(example):
print(p)
it outputs
((0, 1, 2, 4),)
((0, 1, 4), (2,))
((0, 2), (1, 4))
((0,), (1, 2, 4))
((0,), (1, 4), (2,))
((0, 1, 2), (4,))
((0, 1), (2, 4))
((0, 1), (2,), (4,))
((0, 2, 4), (1,))
((0, 4), (1, 2))
((0, 4), (1,), (2,))
((0, 2), (1,), (4,))
((0,), (1, 2), (4,))
((0,), (1,), (2, 4))
((0,), (1,), (2,), (4,))
Finally, with repeated elements:
example = [1, 2, 2]
for p in _partition(example):
print(p)
output:
((1, 2, 2),)
((1,), (2, 2))
((1, 2), (2,))
((1, 2), (2,))
((1,), (2,), (2,))
To remove the duplicates you can run set(_partition(example))
For the sorting on the outer level, I don't think it can be done with generators since we're getting elements one by one and can't compare them before the generator is exhausted.
Post a Comment for "Reconstruct This Generator To Yield Sorted Nested Tuples Instad Of Nested Lists"