How to create a sequential combo box in python?

I have a list ['a', 'b', 'c', 'd'] and I need a list ['a', 'ab', 'abc', 'abcd', 'b', 'bc' , 'bcd', 'c', 'cd', 'd'].

I watched itertools , but I do not see how to do it.

For all combinations, the code will look like this:

from itertools import permutations stuff = ['a','b','c','d'] for i in range(0, len(stuff)+1): for subset in permutations(stuff, i): print(subset) 

What do I need to do to return only sequential combinations? I think I could check the order for each permutation when I go, but that doesn't seem like the best way.

+6
source share
5 answers

Pretty simple:

 stuff = ['a','b','c','d'] print([''.join(stuff[i:j]) for i in range(len(stuff)) for j in range(i+1, len(stuff)+1)]) 

gives

 ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'] 
+5
source

You can do this with a list in understanding:

 >>> [''.join(['a', 'b', 'c', 'd'])[i:j+1] for i in range(4) for j in range(i, 4)] ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'] 

Not sure if you want to do it this way though.

+1
source

I think this should do the trick:

 items = ['a', 'b', 'c', 'd'] combinations = [] for i, x in enumerate(items): combinations.append(x) accum = x for y in items[i+1:]: accum += y combinations.append(accum) 
+1
source

This function does this:

 def subsequences(lst): return [''.join(lst[i: j+1]) for i in range(len(lst)) for j in range(i, len(lst))] >>> subsequences(['a', 'b', 'c']) ['a', 'ab', 'abc', 'b', 'bc', 'c'] >>> subsequences(['a', 'b', 'c', 'd']) ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'] 
+1
source

Another possible solution (without using itertools ), this time using an auxiliary procedure for clarity:

 def combine(lst): return [''.join(lst[0:i+1]) for i in xrange(len(lst))] lst = ['a', 'b', 'c', 'd'] sum([combine(lst[i:]) for i in xrange(len(lst))], []) => ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'] 
+1
source

All Articles