I am working on an exercise which asks me to write a recursive function with min() to return the max item in a list.
def max_rec(L):
if len(L) == 1:
return L[0]
minimum_val = min(L[0], L[-1])
return max_rec(L.remove(minimum_val))
max_rec([1, 3, 4, 6, 2, 8, 0])
When I call on the function, I get an error saying that an object of type 'Nonetype' has no len(). For the list above, the code successfully removes the 0. The error occurs once it begins working on the modified list without the 0.
What is the reasoning for this error?
Thanks
CodePudding user response:
The function remove()
modifies the list directly, similar to append()
and pop()
. It returns None
, so you are modifying the original list and passing None
when recursively calling max_rec()
. The solution is to remove minimum_val
on a separate line and then pass L
.
def max_rec(L):
if len(L) == 1:
return L[0]
minimum_val = min(L[0], L[-1])
L.remove(minimum_val)
return max_rec(L)
print(max_rec([1, 3, 4, 6, 2, 8, 0]))
Hope this answers your question.