Reputation: 5286
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:
for loop
? maybe a list comprehension
Upvotes: 2
Views: 75
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