6

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?

jpp
  • 159,742
  • 34
  • 281
  • 339
Turbotanten
  • 386
  • 3
  • 14

2 Answers2

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
  • 7,171
  • 2
  • 28
  • 38
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
  • 159,742
  • 34
  • 281
  • 339