简体   繁体   中英

Why does this function return different values on repeated calls?

memory = {}
def rec(n):
    if n in memory:
        value = n
    elif n == 1:
        value = 1
    elif n == 2:
        value = 1
    elif n > 2:
        value = rec(n - 2) + rec(n - 1)
    memory[n] = value
    return value

This is the code, and I know it is not entirely a correct recursion code. What I do not understand is that if I call rec(5), it output 7 at the first time, and 5 from the next time. Please can someone help me explain this?

Your problem is you're updating memory when n is already in the memory. The whole process of your first rec(5) is:

rec(5) = rec(3) + rec(4) = rec(1) + rec(2) + rec(4) = 1 + 1 + rec(2) + rec(3)

Until here everything is correct. Then your method will calculate rec(2) where 2 is already in your memory , so your new value for rec(2) is 2.

If you don't understand why, see here:

def rec(n):
    if n in memory:
        value = n
    # ...
    memory[n] = value
    return value

Then it calculates the value of rec(3) , and 3 is also in memory, so rec(3) is now 3

Then rec(5) = 1 + 1 + 2 + 3 = 7

For the second time you run it, since 5 is in memory, so the output is 5.

One possible solution:

def rec(n):
    if n in memory:
        return memory[n]
    elif n == 1:
        value = 1
    elif n == 2:
        value = 1
    elif n > 2:
        value = rec(n - 2) + rec(n - 1)
    memory[n] = value
    return value
memory = {}
def rec(n):
    if n in memory:
        value = memory[n]
    elif n == 1:
        value = 1
    elif n == 2:
        value = 1
    elif n > 2:
        value = rec(n - 2) + rec(n - 1)
    memory[n] = value

    return value

print (rec(5))
print (rec(5))

Now it prints 5 both times. The problem was with value=n while it should be

value=memory[n], 

So,

value=n 

meant that the value of 2 too gets updated to 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM