Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Get all combinations of sequential elements of list

Given an array say x = ['A','I','R'] I would want output as an

[['A','I','R'],['A','I'],['I','R'],['A'],['I'],['R']]

What I don't want as output is :

[['A','I','R'],['A','I'],['I','R'],['A','R'],['A'],['I'],['R']]  # extra ['A','R'] which is not in sequence .

Below is the code which gives the output I don't want:

letter_list = [a for a in str]
all_word = []
for i in xrange(0,len(letter_list)):
    all_word = all_word + (map(list, itertools.combinations(letter_list,i))) # dont use append. gives wrong result.
all_word = filter(None,all_word) # remove empty combination
all_word = all_word + [letter_list] # add original list

My point is I only want combinations of sequences. Is there any way to use itertools or should I write custom function ?

like image 899
minatverma Avatar asked Oct 01 '15 08:10

minatverma


2 Answers

Yes, you can use itertools:

>>> x = ['A', 'I', 'R']
>>> xs = [x[i:j] for i, j in itertools.combinations(range(len(x)+1), 2)]
>>> xs
[['A'], ['A', 'I'], ['A', 'I', 'R'], ['I'], ['I', 'R'], ['R']]
>>> sorted(xs, key=len, reverse=True)
[['A', 'I', 'R'], ['A', 'I'], ['I', 'R'], ['A'], ['I'], ['R']]

Credit: answer by hochl

like image 187
Asclepius Avatar answered Sep 28 '22 19:09

Asclepius


Try to use yield:

x = ['A','I','R']

def groupme(x):
    s = tuple(x)
    for size in range(1, len(s) + 1):
        for index in range(len(s) + 1 - size):
            yield list(x[index:index + size])

list(groupme(x))

>>> [['A'], ['I'], ['R'], ['A', 'I'], ['I', 'R'], ['A', 'I', 'R']]
like image 23
xiº Avatar answered Sep 28 '22 18:09

xiº