Skip to content
Advertisement

One line repeating counter with itertools?

I want to write an infinte generator using itertools that combines a the count and repeat iterators, by repeating each number n times before incrementing. Is there a more concise way to do it than what I came up with?

from itertools import *
def repeating_counter(times):
    c = count()
    while True:
        for x in repeat(next(c), times):
            yield x

>>> rc = repeating_counter(2)
>>> next(rc)
0
>>> next(rc)
0
>>> next(rc)
1
>>> next(rc)
1

Advertisement

Answer

Use integer division!

def repeating_counter(times):
    return (x // times for x in count())
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement