Sum of range(1,n,2) values using recursion
The problem with your recursion is that you're returning n
rather than the value in the range (list) that you're currently on, this poses a problem since n
is not inclusive within the range and should not be added to the final total
Ideally you need to reverse the logic and traverse it the same way your range does
def func(start,end, step):
if(start >= end):
return 0
return start + func(start + step, end, step)
You want to compute the sum of all odd integers from 1 up to, but not including, n.
This leaves 2 possibilities:
- If
n
is <= 1, there are no numbers to sum, so the sum is 0. - The highest number that might be included in the list is
n-1
, but only if it is odd. Either way, the rest of the sum is "the sum of all odd integers from 1 up to, but not including, n-1" (sound familiar?)
This translates to:
def f1(n):
if n <= 1:
return 0
else:
isOdd = (n-1)%2==1
return f1(n-1) + (n-1 if isOdd else 0)
The tricky part is excluding the upper bound. If the upper bound is your only parameter n
, you have to know when it's the first call, and when it's an intermediate (recursive) call. Alternatively, if inner functions are okay, you could instead just count from 1 up until you hit n
:
def function1(n):
def inner(i):
return 0 if i >= n else i + inner(i + 2)
return inner(1)