2

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)]
hlovdal
  • 26,565
  • 10
  • 94
  • 165
Tam211
  • 723
  • 5
  • 10
  • 27

2 Answers2

4

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
Lily Chung
  • 2,919
  • 1
  • 25
  • 42
1

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))
Paul Hankin
  • 54,811
  • 11
  • 92
  • 118