Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cycle list in python? [duplicate]

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?

like image 254
Turbotanten Avatar asked Jun 10 '18 12:06

Turbotanten


2 Answers

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

like image 63
Druta Ruslan Avatar answered Nov 08 '22 10:11

Druta Ruslan


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']]
like image 28
jpp Avatar answered Nov 08 '22 09:11

jpp