Ludium
Sign In
Introduction to Computational Thinking and Data Science
Optimization
01Optimization Models and the Knapsack Problem02Brute-Force Knapsack and the Exponential Power Set03Greedy Algorithms: One Function, Any Definition of Best04Lambda Keys and Why Greedy Can Miss the OptimumProblem set0/10MIT problem set0/2
01The Knapsack Search Tree: Every Combination, 2ⁿ Nodes02Recursive maxVal: An Exhaustive Search That Beats Greedy03Memoization: Turning Slow Fibonacci into fastFib04Overlapping Subproblems and the Memoized KnapsackProblem set0/10MIT problem set0/2

Coding challenges on brute force and dynamic programming

Problem 1Memoization: Turning Slow Fibonacci into fastFib

Fill a Fibonacci Table from the Bottom Up

Write the function fibTable(n) that returns a list of length n + 1 whose entry at index i is the Fibonacci number fib(i)\text{fib}(i)fib(i), using the lecture's convention fib(0)=fib(1)=1\text{fib}(0) = \text{fib}(1) = 1fib(0)=fib(1)=1.

Assume n is a non-negative int. Memoization fills a table on the way down a recursion; here fill it on the way up: start from the base cases and compute each new entry from entries already in the list. Do not use recursion: fibTable must work for n as large as 3000, far deeper than Python's recursion limit.

print(fibTable(6))          # [1, 1, 2, 3, 5, 8, 13]
print(fibTable(0))          # [1]
print(fibTable(120)[-1])    # 8670007398507948658051921
1
2
3
4
5
6
7
8
def fibTable(n):
    """n: an int >= 0.
    Return the list [fib(0), fib(1), ..., fib(n)], where fib(0) = fib(1) = 1,
    built without recursion."""
    pass

Scratchpad— run any Python to test ideas
1
2
3
4
5
# Scratchpad — run any Python here to test ideas.
# Anything you write below stays separate from the problem's tests.

print("hello, world")

Python runtime ready in a moment
Python runtime ready in a moment
Visible tests · 2Examples — click to expand
?
fibTable(6)
?
fibTable(1)
Hidden tests · 3Bodies hidden — pass/fail only
?
Hidden test 1
?
Hidden test 2
?
Hidden test 3