SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Recursion
Exercise:
Programming Exercises
Question:5 | ISBN:9780132576376 | Edition: 2

Question

Recursive List Sum
Design a function that accepts a list of numbers as an argument. The function should recursively
calculate the sum of all the numbers in the list and return that value.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Recursive List Sum Program code:

# Create a function name, calculateSum that accepts a list of numbers as an argument. 
#The function should recursively calculate the sum of all the numbers 
#in the list and return that value.
def calculateSum(numbers):
    if len(numbers) == 1:
        return numbers[0]
    else:
        # Recursive call with the sublist starting from index 1
        sub_sum = calculateSum(numbers[1:])
        
        # Add the first element to the sum of the sublist
        return numbers[0] + sub_sum

# Initialized the values and call the function,calculateSum
numbers = [10, 20, 30, 40, 10]
totalSum = calculateSum(numbers)

#Display output
print("Initialized input values:", numbers)
print("Sum of above numbers:", totalSum)

Executed Output:

Initialized input values: [10, 20, 30, 40, 10]

Sum of above numbers: 110

 

0 0

Discussions

Post the discussion to improve the above solution.