Reputation: 15
is there an easy way in python to cycle a variable in a given range? For example: Given a range(), I want a variable goes like this: 0 1 2 3 2 1 0 1 2 3... till some conditions are satisfied.
Upvotes: 0
Views: 2533
Reputation: 101929
You want to cycle
the sequence 0, 1, ..., n, n-1, ..., 1
.
You can easily build this sequence using chain
from itertools import chain, cycle
def make_base_sequence(n):
base = range(n+1) # 0, ..., n
rev_base = reversed(range(1, n)) # n-1, ..., 1
return chain(base, rev_base) # 0, ..., n, n-1, ..., 1
for x in cycle(make_base_sequence(5)):
print(x)
Sample run:
In [2]: from itertools import chain, cycle
...:
...: def make_base_sequence(n):
...: base = range(n+1)
...: rev_base = reversed(range(1, n))
...: return chain(base, rev_base)
...:
...: for i, x in enumerate(cycle(make_base_sequence(5))):
...: print(x, end=' ')
...: if i > 20:
...: break
...:
0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1
Upvotes: 1
Reputation: 43447
import itertools
def f(cycle_range, condition_func):
sequence = range(cycle_range) + range(cycle_range)[-2:0:-1]
cycle_generator = itertools.cycle(sequence)
while not condition_func():
yield next(cycle_generator)
def condition_func():
"""Checks some condition"""
Essentially, you just want to loop and constantly check the condition. And each time yeild the next item from the cycle. Now, admittedly there are better ways to check a condition than a function call, but this is just an example.
Upvotes: 0
Reputation: 19733
you need itertools.cycle:
demo:
>>> import itertools
>>> count = 0
>>> for x in itertools.cycle(range(3)):
... if count == 10:
... break
... print x,
... count += 1
...
0 1 2 0 1 2 0 1 2 0
Upvotes: 0
Reputation: 2419
import time
def cycle(range_):
num = -1
current = 0
a=time.time()
while 1:
print current
if current in (0, range_):
num*=-1
current += num
if time.time() - a > 0.002:
break
cycle(3)
output:
0 1 2 3 2 1 0 1 2 3 2 1 0 1 2 3 2 1 0 1 2 3 2 1 0 1 2 3 2
Upvotes: 0
Reputation: 1056
itertools.cycle
is a good start. Else you can program it yourself:
cycle = [0,1,2,3,2,1]
i = 0
while some_condition:
value = cycle[i]
i = (i+1) % len(cycle)
#do stuff
Upvotes: 0
Reputation: 249133
You want itertools.cycle()
, see here:
https://docs.python.org/2/library/itertools.html#itertools.cycle
Upvotes: 0