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:
Y Daniel Lang
Chapter:
5.recursion
Exercise:
Programming Excercises
Question:12 | ISBN:978013274719 | Edition: 6

Question

(Find the largest number in a list) Write a recursive function that returns the largest integer in a list. Write a test program that prompts the user to enter a list of integers and displays the largest element.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Find the largest number in a list program code:

#Recursive function to find the largest integer in a list.
def findLargestNum(nums):
     # Base case: If the list has only one element, return that element.
    if len(nums) == 1:
        return nums[0]

    # Recursive case: Find the largest integer in 
    #the sub-list from index 1 onwards,
    # and compare it with the first element. 
    #Return the larger of the two.
    return max(nums[0], findLargestNum(nums[1:]))


# Prompt the user for input
nums = input("Enter a list of integer numbers: ").split()
nums = [int(num) for num in nums]

# Find the largest element in the list
largest = findLargestNum(nums)

# Display the result
print(f"The largest element in the list is: {largest}")

Executed Output 1:

Enter a list of integer numbers: 10 3 5 55 3 22 99 122 9 5 2 1 
The largest element in the list is: 122

Executed Output 2:

Enter a list of integer numbers: 5 4 3 11 2
The largest element in the list is: 11

 

0 0

Discussions

Post the discussion to improve the above solution.