Skip to content Skip to sidebar Skip to footer

Python, Recursively Reduce A List (combinations/permutations)

I'm trying to make a generic function that would reduce a list like so : func(['a','b','c'],str.join) # --> ['a','b','c','ab','ac','bc','abc'] func(['a','b','c'],lambda: a,b:a+

Solution 1:

itertools.combinations will give you all combinations of a certain length. We take all the combinations for each possible sublist length. We then map the function you were interested in (the lambda function, or in this case "x".join) to each of the generated combinations.

>>> import itertools as it
>>> a = ['a','b','c']
>>> l = [map("x".join, list(it.combinations(a, l))) for l inrange(1,len(a)+1)]
>>> l
[['a', 'b', 'c'], ['axb', 'axc', 'bxc'], ['axbxc']]

Now l is a list of lists that we want to flatten:

>>> [ x for y in l for x in y]['a', 'b', 'c', 'axb', 'axc', 'bxc', 'axbxc']

Solution 2:

How's this?

>>>import itertools>>>deffunc(mylist, letter):...    L = []...for i inrange(len(mylist)):...            L.append(list(itertools.combinations(mylist,i+1)))...return [letter.join(i) for i in itertools.chain.from_iterable(L)]...>>>func(['a','b','c'], 'x')
['a', 'b', 'c', 'axb', 'axc', 'bxc', 'axbxc']

Post a Comment for "Python, Recursively Reduce A List (combinations/permutations)"