Suppose I begin with the following list [a,b,c], and that I from this list want to create the following list [[a,b,c], [c,a,b], [b,c,a]]which contains all the cycles of the original list. How can I do that in the most efficient way possible?
Asked
Active
Viewed 1,840 times
5
jpp
- 147,904
- 31
- 244
- 302
Turbotanten
- 356
- 3
- 13
-
you try something ? – Druta Ruslan Jun 10 '18 at 12:10
-
I could define a function that rotates a list ` def rotate(l, n): return l[n:] + l[:n]` but to me it seem like there should be a more efficient way of doing this. – Turbotanten Jun 10 '18 at 12:11
-
Are you just looking for permutations of a list? Cycling typically refers to something else. – Carcigenicate Jun 10 '18 at 12:17
2 Answers
6
with list comprehension or you want something special ?
lst = ['a','b','c']
n_lst = [lst[x:] + lst[:x] for x in range(len(lst))]
print(n_lst)
Output
[['a', 'b', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b']]
Something special for all peremutations
import itertools
list(itertools.permutations(lst))
Output
[
('a', 'b', 'c'),
('a', 'c', 'b'),
('b', 'a', 'c'),
('b', 'c', 'a'),
('c', 'a', 'b'),
('c', 'b', 'a')
]
Also i check the time of execution of a list comprehension and of build-in function rotate from collections.deque object from @jpp answer.
lst = list(range(10000))
# list comprehension time
1.923051118850708
# rotate from collections.deque time
1.6390318870544434
rotate is faster
Druta Ruslan
- 6,597
- 2
- 25
- 35
3
Using collections.deque and its method rotate:
from collections import deque
A = deque(['a', 'b', 'c'])
res = []
for i in range(len(A)):
A.rotate()
res.append(list(A))
print(res)
[['c', 'a', 'b'],
['b', 'c', 'a'],
['a', 'b', 'c']]
jpp
- 147,904
- 31
- 244
- 302