def find_max(nums: [int]) -> int:
'''
Finds the maximum value in the given list of integers,
or None if the list is empty
'''
largest = None

for num in nums:
if largest == None or num > largest:
largest = num

return largest

Rewrite the find_max function so that it uses recursion to work its way through the list instead of using a loop. Your rewritten function should accept the same kinds of inputs (i.e., a one-dimensional list of integers) and generate the same outputs. In your view, is this a problem that's well-suited to a recursive solution in Python.

Respuesta :

Answer:

The program in recursion is:

def find_max(nums):

    if len(nums) == 0:

         return "None"

    elif len(nums) == 1:

         return nums[0]

    else:

         return max(nums[0],find_max(nums[1:]))

Explanation:

This line defines the function

def find_max(nums):

This checks if the list is empty.

    if len(nums) == 0:

If yes, it returns "None"

         return "None"

If the list has just one element

    elif len(nums) == 1:

It returns the only element as the maximum

         return nums[0]

If the list has numerous elemente

    else:

The maximum is determined recursively

         return max(nums[0],find_max(nums[1:]))

To the (b) part:

This program does not necessarily need to be done recursively because the max built-in function can be used to determine the maximum of the list in just one line of code and it is more efficient.

ACCESS MORE