![]() |
I am getting the wrong answer, and not sure why - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: I am getting the wrong answer, and not sure why (/thread-30781.html) |
I am getting the wrong answer, and not sure why - riskeay - Nov-05-2020 This is my code: 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)] n = 0 results = [] for t in triangles(): results.append(t) n = n + 1 if n == 10: break for t in results: print(t)The answer I want to get: [1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] The output of that code: [0, 1, 0] [0, 1, 1, 0] [0, 1, 2, 1, 0] [0, 1, 3, 3, 1, 0] [0, 1, 4, 6, 4, 1, 0] [0, 1, 5, 10, 10, 5, 1, 0] [0, 1, 6, 15, 20, 15, 6, 1, 0] [0, 1, 7, 21, 35, 35, 21, 7, 1, 0] [0, 1, 8, 28, 56, 70, 56, 28, 8, 1, 0] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] I try to debug that code,The value of 'results' changes from [[1]] into [[0,1]] when the N.insert(0,0) is ran, why? [Image: 2c45be315c6034a8bbdb67c1dc13495409237612.jpg] RE: I am getting the wrong answer, and not sure why - riskeay - Nov-05-2020 The next step [Image: bf35b119ebc4b74508736756d8fc1e178b82156f.jpg] RE: I am getting the wrong answer, and not sure why - bowlofred - Nov-05-2020 N is a list and is therefore mutable. In triangles() you hand back an object in line 4 (yield N), but then in line 5 you modify that object. If the caller didn't make a copy yet, their copy of the object is changed as well. A simple change here would be to return a copy of the list so that the caller's object can't be modified later by the function. yield list(N) RE: I am getting the wrong answer, and not sure why - deanhystad - Nov-05-2020 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". 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])] |