151k views
3 votes
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.

User Monolo
by
2.8k points

2 Answers

9 votes

Final answer:

Yes, this problem is well-suited to a recursive solution in Python. To rewrite the find_max function using recursion, we can first check the base case, which is when the list is empty. In this case, we return None. Otherwise, we compare the first element of the list with the maximum of the rest of the list obtained by recursively calling the find_max function.

Step-by-step explanation:

Yes, this problem is well-suited to a recursive solution in Python. To rewrite the find_max function using recursion, we can first check the base case, which is when the list is empty. In this case, we return None. Otherwise, we compare the first element of the list with the maximum of the rest of the list obtained by recursively calling the find_max function.

Here is the recursive implementation:

def find_max(nums: [int]) -> int:
if len(nums) == 0:
return None
elif len(nums) == 1:
return nums[0]
else:
max_rest = find_max(nums[1:])
if nums[0] > max_rest:
return nums[0]
else:
return max_rest

User Jordanvrtanoski
by
3.1k points
2 votes

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:]))

Step-by-step 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.

User Iamnagaky
by
2.9k points