Search code examples
pythonlistgeneratorpascals-triangle

Why does my generator function always return the same value?


I want to build a generator for Bernoulli's triangle, the number i in the j line in the triangle is the partial sum of the first i numbers in pascal's triangle in line j.

the triangle would look like this :

enter image description here

which would be represented in python by lists :

[[1], [1,2], [1,3,4], [1,4,7,8] 

My generator function returns [1] as the first output, which is correct, but then it returns [] all the time!

That's my code:

def next_row(row):
    n = len(row)
    new_row = [row[0]] + [row[i] + row[i+1] for i in range(n - 1)] + [row[-1]]
    return new_row


def generate_pascal():
    row =[1]
    while True:
        yield row
        row=next_row(row)


def generate_bernoulli():

    row=next(generate_pascal())
    n=len(row)
    while True:
        yield row
        row=[row[0]+sum(row[0:i]) for i in range(n-1)]

Solution

  • Firstly, you only called next once, rather than calling it every iteration. Secondly, you never updated row in each iteration. In addition, your partial sum and yield were interchanged. I fixed these by putting the call to next inside the while loop, and initializing the pascal generator outside it. Finally, your sum was a little off; I fixed this as well. The correct code is below:

    def generate_bernoulli():
        pascal = generate_pascal()
        while True:
            row=next(pascal)
            n=len(row)
            row=[sum(row[0:i+1]) for i in range(n)]
            yield row