Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite generator in Python for days of week

I have seen similar questions, my is little bit more practical, I would like to iterate over range of week days over and over again.

So far my iterator is not cyclic, help me please to resolve this.

def day_generator():
    for w in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']:
        yield w;

g = day_generator()
print g.next() 
like image 934
Rudziankoŭ Avatar asked Mar 14 '23 04:03

Rudziankoŭ


1 Answers

You can use itertool's cycle: https://docs.python.org/2/library/itertools.html#itertools.cycle

import itertools
def day_generator():
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    for day in itertools.cycle(days):
        yield day

Long story short(and as mentioned in comments) it is really enough to make:

day_generator = itertools.cycle(days)

Thanks @FlavianHautbois

like image 157
Andrey Rusanov Avatar answered Mar 19 '23 22:03

Andrey Rusanov