简体   繁体   中英

Python: Printing all permutations of list while maintaining order and sequence

The question is as follows: Given a list of integers (1-n), print all the permutations of lists while maintaining order and sequence.

Ex: lst = [1,2,3] (n is 3 in this case)

output:

[1,2,3]
[1,2]
[2,3]
[1]
[2]
[3]

What's going on here is that the largest group is printed first (includes all the integers up to n), and only 1,2,3 would be accepted since it maintains the sequence and doesn't change the order. Next the groups of two. In this case 1,2 and 2,3. Again the sequence is maintained. Finally the groups of 1 which will just be all the integers.

I am not sure how to go about solving this question since it is different from printing all permutations, which would make cases such as 2,1 and 3,2 acceptable; however this does not maintain sequence. Furthermore, 1,3 would not be accepted, since the number after 1 is 2.

Any help would be appreciated!

You can iterate over all possible start and end indices:

lst = [1,2,3]
combo = []
for size in range(len(lst),0,-1):
  for start in range(len(lst)-size+1):
    combo.append(lst[start:start+size])
print(combo)

This outputs:

[[1,2,3],[1,2],[2,3],[1],[2],[3]]

This code seems to work for me:

for x in range(len(lst)):
    for y in range(x+1):
        print(lst[y:y+len(lst)-x])

or using list comprehension:

finalList = [lst[y:y+len(lst)-x] for x in range(len(lst)) for y in range(x+1)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM