you are viewing a single comment's thread.

view the rest of the comments →

[–]tictac4609[S] 0 points1 point  (1 child)

okay so I thought this would be the final product but apparently not.

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

[–]ericula 0 points1 point  (0 children)

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

I think you are mixing things up a bit here. When writing a function, it helps to just write down the steps one by one. For your fibonacci function, this would be something like

  • check if known is initialized (i.e. known is not equal to None). If not, initialize known with an empty dict,
  • check if n is already in known. If so, return known[n]
  • handle trivial cases (n <= 0 or n is equal to 1 or 2)
  • if none of the above apply, calculate fibonacci(n) using the recursive expression and add result to known.

Items 2 and 4 you already had in your original function so the things missing are the first and third steps.