(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.
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