Python list comprehension - need elements skipped combinations

128 views Asked by At

For this input list

[0, 1, 2, 3, 4, 5]

I need this output

[[0, 2],
 [0, 3],
 [0, 4],
 [0, 5],
 [1, 3],
 [1, 4],
 [1, 5],
 [2, 4],
 [2, 5],
 [3, 5],
 [0, 2, 3],
 [0, 3, 4],
 [0, 4, 5],
 [1, 3, 4],
 [1, 4, 5],
 [2, 4, 5],
 [0, 2, 3, 4],
 [0, 3, 4, 5],
 [1, 3, 4, 5]]

I have tried this code,

for k in range( 0, 5 ):
    for i in range( len( inputlist ) - ( 2 + k ) ):
        print [inputlist[k], inputlist[i + ( 2 + k )]]
    for i in range( len( inputlist ) - ( 3 + k ) ):
        print [inputlist[k], inputlist[i + ( 2 + k )], inputlist[i + ( 3 + k )]]
    for i in range( len( inputlist ) - ( 4 + k ) ):
        print [inputlist[k], inputlist[i + ( 2 + k )], inputlist[i + ( 3 + k )], inputlist[i + ( 4 + k )]]

I need skipped patterns, 1,2,3 --> 1,3 1,2,3,4 --> [1,3],[1,4],[2,4]

ie, first element, third element and so on.

How to generalize this? Help is appreciated

2

There are 2 answers

1
fferri On BEST ANSWER

Try to describe with words your problem.

From what I understand from your example:

def good(x): return x[0]+1!=x[1] and all(i+1==j for i,j in zip(x[1:],x[2:]))

from itertools import combinations
[i for j in range(2,5) for i in filter(good, combinations(l,j))]

[(0, 2), (0, 3), (0, 4), (0, 5), (1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5), (0, 2, 3), (0, 3, 4), (0, 4, 5), (1, 3, 4), (1, 4, 5), (2, 4, 5), (0, 2, 3, 4), (0, 3, 4, 5), (1, 3, 4, 5)]

0
Ajay On
from itertools import combinations

a=range(6)
combs=[list(combinations(a,j)) for j in range(2,5)]

combs1=[list(i) for elem in combs for i in elem if (len(i)==2 and i[1] -i[0] >1)  or (len(i)>=3 and i[-1]-i[-2] ==1 and i[1] -i[0]>1 and i[2]-i[1] ==1)]

print combs1
#Output
[[0, 2], [0, 3], [0, 4], [0, 5], [1, 3], [1, 4], [1, 5], [2, 4], [2, 5], [3, 5], [0, 2, 3], [0, 3, 4], [0, 4, 5], [1, 3, 4], [1, 4, 5], [2, 4, 5], [0, 2, 3, 4], [0, 3, 4, 5], [1, 3, 4, 5]]