Search code examples
pythoniteratorgenerator

Python Ruler Sequence Generator


I have been struggling for a long time to figure how to define a generator function of a ruler sequence in Python, that follows the rules that the first number of the sequence (starting with 1) shows up once, the next two numbers will show up twice, next three numbers will show up three times, etc.

So what I am trying to get is 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7 etc.

I understand that the way to do this is to have two separate count generators (itertools.count(1)) and then for every number in one generator yield number from the other generator:

def rul():
    num = itertools.count(1) 
    repeator = itertools.count(1)
    for x in range(next(repeator)):
        yield from num

But if I hit next() on this function, I get back just the regular 1,2,3,4.. sequence...

Any help on this would be appreciated.


Solution

  • how about regular old python with no itertools?

    def ruler():
        counter = 1
        n = 1
        while True:
            for i in range(counter):
                for j in range(counter):
                    yield n
                n += 1
            counter += 1
    

    in my humble opinion this is the clearest and most straighforward solution for these types of situations