Python recursively shorten a list (combinations / permutations)

I am trying to create a generic function that will reduce the list:

func(['a','b','c'],str.join) # --> ['a','b','c','ab','ac','bc','abc'] func(['a','b','c'],lambda: a,b:a+'x'+b) # --> ['a','b','c','axb','axc','bxc','axbxc'] 

I really don't know how to do this. I made several attempts, but no one was successful. I am sure there is a way to do this with a decrease, but it is not very convenient for me to use this function. Here are a few attempts:

 reduce(lambda a,b:[a,b,str(a)+str(b)],['a','b','c']) reduce(str.join,['a','b','c']) 

I think that somewhere there is no recursion.

I do not ask for special code, any help or advice is appreciated. Thanks.

+4
source share
2 answers

itertools.combinations will provide you with all combinations of a certain length. We take all combinations for each possible length of the subexpression. Then we match the function you are interested in (lambda function or in this case "x".join ) for each of the generated combinations.

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

Now l is the list of lists we want to flatten:

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

Like this?

 >>> import itertools >>> def func(mylist, letter): ... L = [] ... for i in range(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'] 
+3
source

Source: https://habr.com/ru/post/1486561/


All Articles