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_tuple hack, but could you help me to make it 'natively' inside the generator ?
def _partition(collection):
#from here : https://stackoverflow.com/questions/19368375/set-partitions-in-python/61141601"
if len(collection) == 1:
yield [ collection ]
return
first = collection[0]
for smaller in _partition(collection[1:]):
# insert `first` in each of the subpartition's subsets
for n, subset in enumerate(smaller):
yield smaller[:n] + [[ first ] + subset] + smaller[n+1:]
# put `first` in its own subset
yield [ [ first ] ] + smaller
def to_tuple(lst):
return tuple(to_tuple(i) if isinstance(i, list) else i for i in lst)
## using it
exemple = [0,0,1,4]
pp = [sorted(p) for p in _partition(exemple)]
result = to_tuple(pp)