I can’t understand this code. I thought it had to do a loop until it gets to the base number. So, if you start with 6, then result should be 6 + (6 - 1) = 11. But there’s no 11 in the results list. If it’s counting from 0, then the first number should be 1 + (1 -1) = 1, which is in the list. And the next number results in 2 + ( 2- 1) = 3, which is in the list. But 3 + (3 - 1) = 5, which is not in the list. What am I doing wrong? Thanks
if(k > 0):
result = k + tri_recursion(k - 1)
result = 0
print("\n\nRecursion Example Results")
It helps to surround your code in triple backticks in order to have it show properly in these messages.
One useful way to imagine recursion is that there are lots and lots of separate functions. Each one does one tiny part of the job; and each one calls another one to do the rest of the job. Try to write these functions:
... # Implement this function: k is always going to be zero
... # Implement this function; k will be one, and you should call
# the previous function to do some of the work. Also, use k in
# the function here, rather than assuming that it's one.
... # You get the idea I hope
# and do the same for 4 to 6
Once you’ve implemented each of these functions, you should be able to see the pattern in them. Then you’ll be able to bring them all together into the original tri_recursion function, which will look at k and decide whether to behave like tri_recursion_0 or one of the others.
Have a shot at that, and come back to us with the results!
You function working just fine. You left off the last 2 results: 15 (10+5) and 21 (15+6). To see what is going on better, put print(k) before the first result line. There are really two repetition cycles: first 7 calls, then 6 returns. (The call to and return from k=0 is not printed.)