iam.Carrot
iam.Carrot

Reputation: 5286

Get combinations of a list of number in a sequence

Hi I am working with python. I am working with a list of numbers

A = [7,9,6,8]

I want to get the permutations of the numbers that are in a sequential manner. Desired output is as below:

[(6), (7), (8), (9), (6, 7), (7, 8), (8, 9), (6, 7, 8), (7, 8, 9)]

My code is as below:

>>> import itertools
>>> A = [6,8,7,9]
>>> def comb(myc: list):
        retcol = []
        for i in range(1,len(myc)):
            retcol += list(itertools.combinations(myc,i))
        return retcol

>>> S = sorted(A, key=int)
>>> comb(S)
[(6,), (7,), (8,), (9,), (6, 7), (6, 8), (6, 9), (7, 8), (7, 9), (8, 9), (6, 7, 8), (6, 7, 9), (6, 8, 9), (7, 8, 9)]
>>> 

[(6,), (7,), (8,), (9,), (6, 7), (6, 8), (6, 9), (7, 8), (7, 9), (8, 9), (6, 7, 8), (6, 7, 9), (6, 8, 9), (7, 8, 9)]

I have 2 questions:

  1. How can I get only the combinations that are in a sequence like shown in the desired output above.
  2. Is there a better way to get such kinda result without putting in an explicit for loop? maybe a list comprehension

Upvotes: 2

Views: 75

Answers (1)

Kodiologist
Kodiologist

Reputation: 3495

How about

l = sorted(A)
[l[j : j + i] for i in range(1, len(l)) for j in range(len(l) - i + 1)]

This yields

[[6], [7], [8], [9], [6, 7], [7, 8], [8, 9], [6, 7, 8], [7, 8, 9]]

which isn't quite what you asked for, but I'm guessing you just made mistakes (e.g., having the first element be a bare number instead of a one-element tuple or one-element list).

Upvotes: 3

Related Questions