0

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!

1
  • 1
    just put a print statement as your first statement, to log your input parameters... And everything will become clear ;-p Commented Oct 19, 2020 at 8:11

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.