I understand the basic principle of recursion, but I'm having trouble implementing it in practice.
I understand this first case perfectly fine. It works because n is constantly getting closer to 0.
def faculty(n):
# Base case
if n == 0:
return 1
# Recursive call
else:
return n * faculty(n-1)
print(faculty(3))
But say I want to calculate (1)+(1/2)+(1/3)+(1/4)+(1/5)+...+(1/n) . Using the below function I only get the very first part (0,1) and then it stops. Obviously it'll stop because it's <= 1. However, if I change it to "if n==1:" it never stops recurring, because n is never 1 (runtime error). I think the problem is that I need n to be 9 (in this example) after the first calculation, but how do I get n = 9 and at the same time get 1/9 as a result for the calculation? Does this make any sense to anyone? I fear I might be rambling :confused:
#n is always >= 1
def sum(n):
if n <= 1:
return n
else:
return 1 + sum(1/n-1)
print(sum(10))
I've got the same problem with trying to calculate 1*1 + 2*2 + 3*3 + 4*4 + n*n. The part-result(correct term?) differs from what I need n to be, and I have yet to figure out how to adjust for it.
My math skills have been degrading for a few years due very low usage. Harmonic numbers > me.