Reputation: 11
initialValues = input('Please enter a space separated set of values for y, h and g(0): ')
values = []
values.append(initialValues)
theValues = []
for item in values:
item = item.split(' ')
for index in range(len(item)):
item[index] = int(item[index])
theValues.append(item)
y = theValues[0][0]
h = theValues[0][1]
g0 = theValues[0][2]
def Sumrecur(y,h,g0):
if y == 0 :
return g0
else:
sum = 0
for k in range(1,y):
sum = sum + Sumrecur(k,h,g0)*h
return sum
Sumrecur(y,h,g0)
this is a function i'm currently working on. I'm confused as the return sum command doesn't work. Is there anything wrong with the code?? Sorry it might sound silly to some of you but I really don't know how to fix this. thanks before!
Upvotes: 0
Views: 311
Reputation: 417
TL;DR :
I would try using range(0,y)
in your for loop.
BREAKDOWN:
Your recursion depends on the value of y
and only ends whenever y
equals 0 .
Lets see how the recursions are called using an example
STEP 1
Sumrecur(3,1,1)
will call Sumrecur(1,1,1)
and Sumrecur(2,1,1)
STEP 2a :
Sumrecur(1,1,1)
calls nothing
STEP 2b :
Sumrecur(2,1,1)
calls Sumrecur(1,1,1)
STEP 3:
Sumrecur(1,1,1)
calls nothing
You see what the issue is ? The value of y never equals 0 , so it never enters the
if y == 0 :
return g0
I would try using range(0,y)
in your for
loop.
Upvotes: 0
Reputation: 638
Once you've gone 1 recursion deep you need to return multiple times to actually return the value. Basically you've returned the value to the last recursion but this isn't the original one you called so there will be no output. Maybe write to a global variable or print the value instead.
Upvotes: 1