Python recursion function for newbie

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

``````def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")
tri_recursion(6)
``````

output:

``````Recursion Examples Results
1
3
6
10
``````

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:

``````def tri_recursion_0(k=0):
... # Implement this function: k is always going to be zero

def tri_recursion_1(k=1):
... # 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.

def tri_recursion_2(k=2):
... # 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!

1 Like

Look at the code. It doesn’t say `result = k + (k - 1)`, it says `result = k + tri_recursion(k - 1)`.

So if you start with `tri_recursion(6)`, it’ll return the result of `6 + tri_recursion(6 - 1)`.

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

Oh I’m starting to see. It’s like
6 + (5 + 4 + 3 + 2 + 1) = 21
5 + (4 + 3 + 2 + 1) = 15
4 + (3 + 2 + 1) = 10
etc.
Like a factorial but with addition and subtraction through the if loop.

Yes! That’s the goal you’re looking for, and the parentheses are doing a great job of showing the recursion. Now it’s time to implement!