I cannot understand why this returns 42. I've asked a friend, I've traced it in PythonTutor...still makes no sense. Why doesn't it just return 9 bc 6 - 1 = 5, 6 - 2 = 4, 5 + 4 = 9? Why does it keep looping through? What is waiting for? How does it know where to stop?
def mystery(n):
if n == 0:
return 2
elif n == 1:
return 4
else:
return mystery(n-1) + mystery(n-2)
print(mystery(6))
This is called a recursive function. It calls itself (with new parameters) until it hits one of the "base cases" n==0
or n==1
.
mystery(0) == 2
mystery(1) == 4
mystery(2) = mystery(1) + mystery(0) = 6
mystery(3) = mystery(2) + mystery(1) = 10
mystery(4) = mystery(3) + mystery(2) = 16
mystery(5) = mystery(4) + mystery(3) = 26
mystery(6) = mystery(5) + mystery(4) = 42
as @Christian Slater wrote, you wrote a recursive function, you probably are looking for:
def mystery(n):
if n == 0:
return 2
elif n == 1:
return 4
else:
return (n-1) + (n-2)
print(mystery(6))
output: 9
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.