Powersets in Python using itertools

itertools functions return iterators, objects that produce results lazily, on demand. You could either loop over the object with a for loop, or turn the result into a list by calling list() on it: from itertools import chain, combinations def powerset(iterable): “powerset([1,2,3]) –> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)” s = list(iterable) return … Read more

Prevent memory error in itertools.permutation

Try to use the iterator generated by the permutations instead of recreating a list with it : perm_iterator = itertools.permutations(list(graph.Nodes)) for item in perm_iterator: do_the_stuff(item) by doing this, python will keep in memory only the currently used permutation, not all the permutations (in term of memory usage, it is really better 😉 ) On the … Read more

Replace list of list with “condensed” list of list while maintaining order

Here’s a brute-force approach (it might be easier to understand): from itertools import chain def condense(*lists): # remember original positions positions = {} for pos, item in enumerate(chain(*lists)): if item not in positions: positions[item] = pos # condense disregarding order sets = condense_sets(map(set, lists)) # restore order result = [sorted(s, key=positions.get) for s in sets] … Read more

How to turn an itertools “grouper” object into a list

The reason that your first approach doesn’t work is that the the groups get “consumed” when you create that list with list(groupby(“cccccaaaaatttttsssssss”)) To quote from the groupby docs The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous … Read more