LearnFrenzy
Sign in Take a free test

Recursion · Recursion Coding Problems · Question 2

Fibonacci with a memo dictionary in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Write fib(n) with an explicit memo dictionary and print the first 15 terms and fib(100).

Solution
main.py Run
memo = {0: 0, 1: 1}

def fib(n):
    if n not in memo:
        memo[n] = fib(n - 1) + fib(n - 2)
    return memo[n]

print([fib(n) for n in range(15)])
print(fib(100))

Output Verified by running it on Python 3

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
354224848179261915075

The base values seed the memo; every other value is computed once and then looked up.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links