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:4 | ISBN:9780132576376 | Edition: 2

Question

Largest List Item
Design a function that accepts a list as an argument, and returns the largest value in the list.
The function should use recursion to find the largest item.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Largest List Item using recursion function:

# Create a function name,findLargest  that accepts a list as an argument, 
#and returns the largest value in the list. 
def findLargest(list):
    if len(list) == 1:
        return list[0]
    else:
        # Recursive call with the sublist starting from index 1
        sub_max = findLargest(list[1:])
        
        # Compare the first element with the maximum of the sublist
        if list[0] > sub_max:
            return list[0]
        else:
            return sub_max

# Initialize the list of values and
# call the function, findLargest
listValues = [70, 12, 90, 55, 11, 88,1000]
largest = findLargest(listValues)
print("Initialized input values: ", listValues)
print("The largest value in above list is:", largest)

Executed Output:

Initialized input values:  [70, 12, 90, 55, 11, 88, 1000]

The largest value in above list is: 1000

 

0 0

Discussions

Post the discussion to improve the above solution.