Python: creating all ordered list combinations

I am using Python 2.7.

I have a list, and I want all possible ordered combinations.

import itertools
stuff = ["a","b","c", "d"]
for L in range(1, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        print( ' '.join(subset))

This will produce the following result:

a
b
c
d
a b
a c <-- not in correct order
a d <-- not in correct order
b c
b d <-- not in correct order
c d
a b c
a b d <-- not in correct order
a c d <-- not in correct order
b c d
a b c d

But I want only the output to be combinations that are in the same order as the list stuff. For instance. removal of a d, b d, a b dand a c d, because they are not in the correct order as compared to the stufflist ["a", "b", "c", "d"].

I realized using this instead:

import itertools
stuff = ["a","b","c", "d"]
for L in range(1, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        if ' '.join(subset) in ' '.join(stuff): #added line
            print( ' '.join(subset))

Gives me the result I wanted:

a
b
c
d
a b
b c
c d
a b c
b c d
a b c d

But is there a Python built-in method that does what I want?

+4
source share
2 answers

, , , - . , , :

a         # slices[0:1]
b         # slices[1:2]
c         # slices[2:3]
d         # slices[3:4]
a b       # slices[0:2]
b c       # slices[1:3]
c d       # slices[2:4]
a b c     # slices[0:3]
b c d     # slices[1:4]
a b c d   # slices[0:4]

. , , 2- 0 4, , , itertools.combinations . :

for i, j in itertools.combinations(range(len(stuff) + 1), 2):
    print(stuff[i:j])

:

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['b']
['b', 'c']
['b', 'c', 'd']
['c']
['c', 'd']
['d']

, , , . .

, , :

def getCombinations (lst):
    for i, j in itertools.combinations(range(len(lst) + 1), 2):
        yield lst[i:j]

for x in sorted(getCombinations(stuff), key=len):
    print(' '.join(x))
+10

, " ", stuff:

stuff = ["a","b","c", "d"]
# sort stuff here if it not sorted

result = []
for i in xrange(len(stuff)):
    for j in xrange(i+1, len(stuff)+1):
        result.append(stuff[i:j])

# sort the result by length, maybe you don't need it
result = sorted(result, key=len)

for r in result:
    print ' '.join(r)
+2

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


All Articles