简体   繁体   中英

Understanding simple recursive function

I don't understand how the following code have an output of 3?

I get that n %= 5 output 4 which go to the else statement. so it should be return rec(4-1) + rec(4-2) so how does this output 3?

def rec(n):
    n %= 5
    if n <= 1:
        return n
    else:
        return rec(n-1) + rec(n-2)
print(rec(9))

output: 3

When I run a few tests on the code, the value you input re-defines n to be 3. This executes the else statement which produces the values 2 for rec(3-1) and 1 for rec(3-2). This has the function return the value 2+1 which is where your 3 output is coming from.

The best way to solve this kind of problem is to track the recursive calls:

rec(9):
  n = 4 # ( 9 % 5)
  return (rec(3) + rec(2)) # rec(n-1) + rec(n-2)

rec(3):
  n = 3
  return rec(2) + rec(1) # rec(n-1) + rec(n-2)

rec(2):
  n = 2
  return rec(1) + rec(0)

rec(0) = 0

rec(1) = 1

rec(2) = 1

rec(3) = 2

therefore rec(9) = 3

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