简体   繁体   中英

Python recursion with dictionary?

I have a recursion function defined as follows:

def myfunc(n, d):
    if n in d:
        return d[n]
    else:
        return myfunc(n-1,d) + myfunc(n-2,d)

and if I run it with the following parameters:

myfunc(6, {1:1,2:2})

I get this 13, but I expected the sum to be 8? Since the recursion would look something like this:

myfunc(5,d) + myfunc(4,d)
myfunc(4,d) + 2
myfunc(3,d) + 2
2 + 2

which equals = 2 + 2 + 2 + 2 = 8? Could someone explain? Thank you!

myfunc(6,d) == myfunc(5,d) + myfunc(4,d)
            == myfunc(4,d) + myfunc(3,d) + myfunc(3,d) + myfunc(2,d)
            == (myfunc(3,d) + myfunc(2,d)) + (myfunc(2,d) + myfunc(1,d)) + (myfunc(2,d) + myfunc(1,d)) + myfunc(2,d)
            == ((myfunc(2,d) + myfunc(1,d)) + myfunc(2,d)) + (myfunc(2,d) + myfunc(1,d)) + (myfunc(2,d) + myfunc(1,d)) + myfunc(2,d)
            == 2 + 1 + 2 + 2 + 1 + 2 + 1 + 2
            == 13

or if you prefer:

myfunc(1,d) == 1
myfunc(2,d) == 2
myfunc(3,d) == myfunc(2,d) + myfunc(1,d) == 2 + 1 == 3
myfunc(4,d) == myfunc(3,d) + myfunc(2,d) == 3 + 2 == 5
myfunc(5,d) == myfunc(4,d) + myfunc(3,d) == 5 + 3 == 8
myfunc(6,d) == myfunc(5,d) + myfunc(4,d) == 8 + 5 == 13

This is the Fibonacci sequence .

You are picturing your recursion falsely. It looks like this:

myfunc(6, d)
myfunc(5, d) + myfunc(4, d)
myfunc(4, d) + myfunc(3, d)   +    myfunc(3, d) + myfunc(2, d)
myfunc(3, d) + myfunc(2, d)   +    myfunc(2, d) + myfunc(1, d)    +   myfunc(2, d) + myfunc(1, d)        +      2
myfunc(2, d) + myfunc(1, d)   + 2 + 2 + 1 + 2 + 1 + 2
2 + 1 + 2 + 2 + 1 + 2 + 1 + 2
which is 13

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