简体   繁体   English

为什么生成器函数总是返回相同的值?

[英]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 . 我想建立伯努利的三角形生成,数ij在三角线是第一的部分和i号码一致杨辉三角j

the triangle would look like this : 三角形看起来像这样:

在此处输入图片说明

which would be represented in python by lists : 这将在python中由list表示:

[[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! 我的生成器函数返回[1]作为第一个输出,这是正确的,但是随后它始终返回[]

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. 首先,您只调用next ,而不是每次迭代都调用它。 Secondly, you never updated row in each iteration. 其次,您永远不会在每次迭代中更新行。 In addition, your partial sum and yield were interchanged. 此外,您的部分总和与yield已互换。 I fixed these by putting the call to next inside the while loop, and initializing the pascal generator outside it. 我通过将呼叫固定这些next的while循环中,并初始化pascal外面发生器。 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. 您需要计算Pascal三角形行的部分和。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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