+ 1
Confusing itertools and generator
what I'm trying to do here is print something like : what the hekk what the hekk what ... Using yield and next, where am I wrong in this code ? https://code.sololearn.com/c2k9dAANjbR9
9 ответов
+ 3
Sacar ,
here is a sample that shows how we can do the task with cycle(). also it uses a range() object to control the number of outputs, that runs as long as range is returning numbers:
from itertools import cycle
msg = ("what", "the", "hekk")
def get_shift(count, msg):
for i, _ in zip(cycle(msg), range(count)):
yield i
count = int(input()) * len(msg) # input of value 3 repeats and prints the strings from tuple msg 3 times completely
for res in get_shift(count, msg):
print(res)
+ 4
Additionally to what Ani Jona 🕊 said: if you save the iterator/generator/whateveritiscalled you can also use the next function like this:
x=show_msg()
Print(next(x))
Print(next(x))
+ 3
You are restarting the iterator again and again. Do something like:
for m in show_msg():
print(msg)
And don't forget to add a break or it cycles forever.
Alternatively, save the generator object:
msg_iter = show_msg()
And take it from there...
for m in msg_iter:
print(m)
+ 1
Alexander Thiem Aren't they same ??
x = show_msg()
Print(next(x))
And
Print(next(show_msg()))
+ 1
Ani Jona 🕊 you are right, but i want to make it clear that i don't want an Infinite iteration, i want to use 'next' each time
+ 1
You can call next on the generator object, as Alexander Thiem demonstrated. Note that in his and my example, show_msg is called only once! That call provides the generator object; all else is done on that object.
+ 1
It might help to think of generators (in this case for counting only) like this:
Class generator:
__init__(self):
Self.x=1
Next(self):
Self.x+=1
Return self.x
def fun():
Return generator()
Print(fun().next()) #returns a new generator object each time so .next() always results in the starting value
Gen=fun()
Print(gen.next()) #counts upwards in the same object
+ 1
Lothar Wunderbar !!! Thats exactly what i wanted.
0
Thanks Everyone for your time and effort !