简体   繁体   中英

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 :

在此处输入图片说明

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)]

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

You need to compute partial sums of the rows of Pascal's triangle. Here's how I'd write the code.

def partial_sums(xs):
    s = 0
    for x in xs:
        s += x
        yield s

def generate_bernoulli():
    for row in generate_pascal():
        yield list(partial_sums(row))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM