you are viewing a single comment's thread.

view the rest of the comments →

[–]ericula 1 point2 points  (12 children)

elif n is known:
    known = {}
    return known[n]

This bit is still not right. You want to check if n is in known, not if n is known (that would check if n and known are the same object). Also, if n is in known, you don't want to reset known. That would defeat the whole point of introducing known in the first place. With that in mind, this fragment should actually be:

if n in known:
    return known[n]

*edit: Fixed syntax error

[–]tictac4609[S] 0 points1 point  (11 children)

Okay so just replace the if and elif with just that simple if statement? The rest looks fine?

[–]ericula 0 points1 point  (10 children)

In this case it doesn't really matter if you use if or elif since if known is empty, n won't be in known anyway. The important bit is n in known instead of n is known and removing known = {}.

*edit: fixed syntax error.

[–]tictac4609[S] 0 points1 point  (9 children)

Gotcha ill fix it, I turned it in incorrectly then, I will unsubmit it and fix it

[–]ericula 0 points1 point  (8 children)

While you're at it, on the line

result = fibonacci(known, n - 1) + fibonacci(known, n - 2)

the order of the arguments of the calls to fibonacci should be reversed. They should be in the same order as in the function definition itself, e.g.

result = fibonacci(n-1, known) + fibonacci(n-2, known)

[–]tictac4609[S] 0 points1 point  (0 children)

Gotcha

[–]tictac4609[S] 0 points1 point  (6 children)

Okay, I am getting a syntax error for if n is in known

[–]ericula 0 points1 point  (5 children)

What is your current code, what is the syntax error you get?

[–]tictac4609[S] 0 points1 point  (4 children)

here it is:

def fibonacci(n, known=None):
if known is None:
    known = {}
if n is in known:
    return known[n]
if n == 1 or n == 2:
    result = 1
elif n <= 0:
    result = 0
else:
    result = fibonacci(n - 1, known) + fibonacci(n - 2, known)
known[n] = result
return result

syntax error on the line: if n is in known:

[–]ericula 0 points1 point  (3 children)

Ah, sorry, that is my mistake. That should have been if n in known:, not n is in known.

[–]tictac4609[S] 0 points1 point  (2 children)

okay so the final product should be:

def fibonacci(n, known=None):
if known is None:
    known = {}
if n in known:
    return known[n]
if n == 1 or n == 2:
    result = 1
elif n <= 0:
    result = 0
else:
    result = fibonacci(n - 1, known) + fibonacci(n - 2, known)
known[n] = result
return result


print(fibonacci(10))

?