Nov-05-2020, 08:24 PM
(This post was last modified: Nov-05-2020, 08:24 PM by deanhystad.)
This is a fun problem.
Triangles has a list N which it yields. A new N is generated each time triangles is called. HOWEVER, before the new N is generated you insert and append 0 to the old N.
This code prints the desired output because it prints the result of triangles() before they get "corrupted".
Triangles has a list N which it yields. A new N is generated each time triangles is called. HOWEVER, before the new N is generated you insert and append 0 to the old N.
This code prints the desired output because it prints the result of triangles() before they get "corrupted".
def triangles(): N = [1] while True: yield N N.insert(0,0) N.append(0) N = [N[i]+N[i+1] for i in range(len(N)-1)] for i, t in enumerate(triangles()): print(t) if i >= 5: breakAn easy fix to your problem is to create to create a new N at the start of each iteration so you don't mess up the previous.
def triangles(): N = [1] while True: yield N N = (0, *N, 0) N = [N[i]+N[i+1] for i in range(len(N)-1)] # Or this one that uses zip and temporary lists. def triangles(): N = [1] while True: yield N N = [p + n for p, n in zip([0]+N, N+[0])]