Circular iteration on tuple starting from a specific index
guillaume.paulet at giome.fr
guillaume.paulet at giome.fr
Fri Jun 2 04:30:02 EDT 2017
@Gregory Ewing: you were right, your version without *chain* is faster
and I quiet like it :)
```
from timeit import timeit
from itertools import chain, cycle, islice
def cycle_once_with_chain(sequence, start):
return chain(islice(sequence, start, None), islice(sequence,
start))
def cycle_once_without_chain(sequence, start):
return islice(cycle(sequence), start, start + len(sequence))
sequence = tuple(i for i in range(100))
time_with_chain = timeit(
stmt='cycle_once_with_chain(sequence, 50)',
number=1000000, globals=globals()
)
print('Method with *chain* took: ', (time_with_chain /1000000), ' per
call.')
# Method with *chain* took: 5.025957580000977e-07 per call.
time_without_chain = timeit(
stmt='cycle_once_without_chain(sequence, 50)',
number=1000000, globals=globals()
)
print('Method without *chain* took: ', (time_without_chain /1000000), '
per call.')
#Method without *chain* took: 3.5880194699984714e-07 per call.
```
@Ian: Good point here, these two methods only works with sequences
(list, tuple, string...).
I renamed it appropriately in the above sample code :)
More information about the Python-list
mailing list