Reputation: 55
listA = ["A","B","C","D"]
From this, I want the following output only:
["A","B","C"]
["B","C","D"]
["C","D","A"]
["D","A","B"]
I have looked at various questions on permutations here, but I am not able to do achieve this so far. Any help will be appreciated.
Upvotes: 2
Views: 3610
Reputation: 55
Thanks for all your answers. I received one another answer from a friend that I wanted to share here. It goes like this.
listA = ["A","B","C","D"]
listB = listA + [listA[0]] + [listA[1]]
catch = []
for i in range(len(listA)):
A = listB[i]
B = listB[i+1]
C = listB[i+2]
catch.append([A,B,C])
print catch
Upvotes: 0
Reputation: 41168
You could use itertools.cycle
and itertools.islice
.
To get the order you show (as @tobias_k suggested):
>>> from itertools import cycle, islice
>>> listA = ["A","B","C","D"]
>>> [list(islice(cycle(listA), i, i+3)) for i in range(len(listA))]
[['A', 'B', 'C'], ['B', 'C', 'D'], ['C', 'D', 'A'], ['D', 'A', 'B']]
To get an alternative sequential ordering:
>>> it = cycle(listA)
>>> [list(islice(it,3)) for _ in range(len(listA))]
[['A', 'B', 'C'], ['D', 'A', 'B'], ['C', 'D', 'A'], ['B', 'C', 'D']]
Upvotes: 3
Reputation: 1047
another way to do this - brute force,
def permutation(L):
for i in range(len(L)):
x = L[i:i+3]
length = len(x)
if length != 3:
x = x + L[:3-length]
print(x)
L = ["A","B","C","D"]
permutation(L)
Upvotes: 3