Abid Siam
Abid Siam

Reputation: 45

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!

Upvotes: 1

Views: 812

Answers (3)

Normal number sequence from 0 to 2^list size - 1. Map number to binary equivalent. The bit position will correspond to list position. 1 will mean present. 0 absent.

mylist = [0, 1, 2, 3, 4, 5]
n_elem = len(mylist)
n_seqc = (1 << n_elem)
sequencies = [[] for _ in range(n_seqc)]
for seq_idx in range(n_seqc):
    for i in range(n_elem):
        if seq_idx & (1 << i) > 0:
            sequencies[seq_idx].append(mylist[i])

print(sequencies)

Upvotes: 0

Kavan Doctor
Kavan Doctor

Reputation: 187

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]]

Upvotes: 3

MoonMist
MoonMist

Reputation: 1227

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)]

Upvotes: 2

Related Questions