Question

I am trying to create a program that takes a user integer input, creates a list and then using recursion adds the list. The problem is when I put in 6 it comes up with 15 and the answer should be (0+1+2+3+4+5+6) = 21. Why is the math wrong? I think it must be somewhere in the indexing because if you leave off the 6 you do get 15.

#Program which accepts a number from the user
#take the numbers 0 to the number input 
#and gives a total of the numbers

def main():
#Get the number from the user to define upper end of range
    num = int(input('Enter a non-negative integer: '))

#Create the list of numbers
numbers = list(range(0,num, 1))

#Get the sum of the list of numbers
my_sum = range_sum(numbers, 0, - 1)

#Display the total
print('The sum of 0 to', num, 'is: ', my_sum)

def range_sum(num_list, start, end):
if start < end:
    return 0
else:
    return sum(num_list)
#call the main function
main() 
Was it helpful?

Solution

Using tail recursion:

def range_sum(nums, sum=0):
    if not nums:
        return sum
    sum += nums.pop()
    return range_sum(nums, sum)

OTHER TIPS

There is no recursive call in the code. You are using the sum function, which comes defined in Python.

This is a relatively simple function to implement either recursively:

def recursive(n):
    if n == 1:
        return n
    return n + recursive(n - 1)

or iteratively:

def iterative(n):
    return sum(range(n + 1)) # note n + 1 - range excludes the stop argument

which is equivalent to:

def iterative_longhand(n):
    total = 0
    for i in range(n + 1):
        total += i
    return total

or, if a list is a necessity:

def recursive_list_sum(nums):
    if nums:
        return nums[0] + recursive_list_sum(nums[1:])
    return 0

recursive_list_sum(list(range(n + 1)))

Your title says "using recursion", but none of your functions call themselves. You are using recursion neither to build the list nor to add up its contents. This function:

def range_sum(num_list, start, end):
    if start < end:
        return 0
    else:
        return sum(num_list)

called like:

range_sum(numbers, 0, - 1)

is just sum(num_list), as start > end. It is not clear what you are trying to achieve - if it should be recursive, there should be a call to range_sum inside it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top