+ 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

17th Jun 2022, 8:05 AM
Sacar
Sacar - avatar
9 Answers
+ 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)
17th Jun 2022, 1:58 PM
Lothar
Lothar - avatar
+ 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))
17th Jun 2022, 8:30 AM
Alexander Thiem
Alexander Thiem - avatar
+ 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)
17th Jun 2022, 8:26 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Alexander Thiem Aren't they same ?? x = show_msg() Print(next(x)) And Print(next(show_msg()))
17th Jun 2022, 8:44 AM
Sacar
Sacar - avatar
+ 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
17th Jun 2022, 8:50 AM
Sacar
Sacar - avatar
+ 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.
17th Jun 2022, 9:13 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 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
17th Jun 2022, 10:13 AM
Alexander Thiem
Alexander Thiem - avatar
+ 1
Lothar Wunderbar !!! Thats exactly what i wanted.
17th Jun 2022, 3:21 PM
Sacar
Sacar - avatar
0
Thanks Everyone for your time and effort !
17th Jun 2022, 3:22 PM
Sacar
Sacar - avatar