-2

I have to write a fib_memoize(n) function that should be recursive but it should memoize its answer so that it's running time is O(n).
This is what I have:

def fib_memoize(n):
    memo = {}
    if n in memo:
        return memo[n]
    else:
        if n <=2:
            f = 1
        else:
            f = fib_recursive(n-1) + fib_recursive(n-2)

        memo[n] = f
        return f

This is giving me an assertion error saying 1 != 0. What is this pointing to? What am I missing?

This is my fib_recursive function (passes the tests):

def fib_recursive(n):
    if n <=1:
        return n
    else:
        return fib_recursive(n-1) + fib_recursive(n-2)
AChampion
  • 29,683
  • 4
  • 59
  • 75
  • Could you explain to me why I see so many new users with improperly indented `def` lines? – Mad Physicist Apr 20 '18 at 03:34
  • 1
    It seems like the error you are referring to comes from the test framework. It's telling you that an input of 0 should return 1, but isn't, or vice-versa. – Mad Physicist Apr 20 '18 at 03:36
  • just memonize by storing fib numbers in a list. Get the next one by appending the sum of the previous two – Primusa Apr 20 '18 at 03:36
  • 1
    @MadPhysicist because they don't know about `` so just indent the first line to get the pasted code to be formatted as code. – AChampion Apr 20 '18 at 03:36
  • @AChampion. First time I heard about it too. I just click on the little button thingy in the toolbar :) That makes a lot of sense though. – Mad Physicist Apr 20 '18 at 03:37
  • This is a typical case of "How not to use recursion" and especially of "How not to teach recursion". – Klaus D. Apr 20 '18 at 04:09

1 Answers1

1

Memoizing is usually done with a decorator over your original function, e.g.:

import functools

def memoize(fn):
    cache = {}

    @functools.wraps(fn)
    def memoizer(n):
        if n not in cache:
            cache[n] = fn(n)
        return cache[n]
    return memoizer

@memoize
def fib_recursive(n):
    if n <=1:
        return n
    else:
        return fib_recursive(n-1) + fib_recursive(n-2)

This turns the original fib_recursive function into a memoized function.

AChampion
  • 29,683
  • 4
  • 59
  • 75
  • 1
    Or use the one that [comes with python](https://docs.python.org/3/library/functools.html) `@functools.lru_cache`. There's even a Fibonacci example in the docs. – Paul Panzer Apr 20 '18 at 04:00
  • 1
    This isn't really helpful to someone trying to understand basic concepts. – juanpa.arrivillaga Apr 20 '18 at 05:05
  • I'm not familiar with the @functools.lru_cache. As you can tell from my question, I'm still a beginner –  Apr 20 '18 at 15:49