Oscillating values ββin Python
So I need 2 values ββto oscillate back and forth. Say 2
the first time, say the 4
second time. Repeat from above.
So, I wrote the following generator function that works. Each time it is called through next
, it returns the subsequent value and then repeats from the top.
For the sake of knowledge and improvement, NOT opinion, is there a better way? Python always seems to be the best way to go and I love learning them to improve my skills.
The "core code" is just to show an example of a generator used, a generator and is not the main use of a generator.
## Main code
go_Osci = g_Osci()
for i in xrange(10):
print("Value: %i") %(go_Osci.next())
## Generator
def g_Osci():
while True:
yield 2
yield 4
source to share
Yes, there is a better way. itertools.cycle
was specially designed for this task:
>>> from itertools import cycle
>>> for i in cycle([2, 4]):
... print i
...
2
4
2
4
2
4
2
# Goes on forever
You can also enumerate
only use the loop for a certain number of times:
>>> for i, j in enumerate(cycle([2, 4])):
... if i == 10: # Only loop 10 times
... break
... print j
...
2
4
2
4
2
4
2
4
2
4
>>>
source to share
Almost two years after I asked this question, I would like to share what I ultimately came up with to suit my needs. Using inline for
loops to alternate alternating variables was often too static and inflexible for what I needed.
I kept coming back to my generator solution as it turned out to be more flexible in my applications - I could call it next()
anytime, anywhere in my scripts.
Then I applied cycle
in my generator. By "flooding" the generator with a list of desired values ββat instantiation time, I can access variable values ββas needed anywhere in my script. I can also "refill" more instances with different values ββas needed.
An additional advantage is that the underlying code is generic and therefore can be considered an imported module.
I call this construct of using a generator to get variable values ββ"Oscillator".
I hope this can benefit someone in the future.
Python 2.7.10
# Imports #
from __future__ import print_function
from itertools import cycle
# Generators
def g_Oscillator(l_Periods):
"""Takes LIST and primes gen, then yields VALUES from list as each called/next()"""
g_Result = cycle(l_Periods)
for value in g_Result:
yield value
# Main Code
go_52Oscillator = g_Oscillator([5, 2]) ## Primed Ocscillator
go_34Oscillator = g_Oscillator([3, 4]) ## Primed Ocscillator
go_ABCOscillator = g_Oscillator(["A", "B", "C"]) ## Primed Ocscillator
for i in xrange(5):
print(go_34Oscillator.next())
print()
for i in xrange(5):
print(go_52Oscillator.next())
print()
for i in xrange(5):
print(go_ABCOscillator.next())
source to share