Python Forum
I am getting the wrong answer, and not sure why
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I am getting the wrong answer, and not sure why
#4
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:
        break
An 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])]
riskeay likes this post
Reply


Messages In This Thread
RE: I am getting the wrong answer, and not sure why - by deanhystad - Nov-05-2020, 08:24 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 5,408 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  why don't i get the answer i want CompleteNewb 12 5,647 Sep-04-2021, 03:59 PM
Last Post: CompleteNewb
  Make the answer of input int and str enderfran2006 2 2,876 Oct-12-2020, 09:44 AM
Last Post: DeaD_EyE
  Keeps looping even after correct answer mcesmcsc 2 2,804 Dec-12-2019, 04:27 PM
Last Post: mcesmcsc
  python gives wrong string length and wrong character thienson30 2 4,172 Oct-15-2019, 08:54 PM
Last Post: Gribouillis
  I'm getting a wrong answer don't know where the bug is 357mag 4 3,938 Jul-07-2019, 11:21 PM
Last Post: DeaD_EyE
  How to answer subprocess prompt Monty 8 20,341 Feb-14-2018, 09:59 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020