I wrote this and its working fine with everything but when I have an empty list
in a given list(given_list=[[],1,2,3]
) it saying index is out of range. Any help?
I assume that the max element of an empty list is negative infinity.
This assumption will deal with the cases like [], [1,2,[],5,4,[]]
def find_max(L):
if len(L) == 0:
return float("-inf")
elif len(L) == 1:
if isinstance(L[0], list):
return find_max(L[0])
else:
return L[0]
elif len(L) == 2:
if isinstance(L[0], list):
firstMax = find_max(L[0])
else:
firstMax = L[0]
if isinstance(L[1], list):
lastMax = find_max(L[1])
else:
lastMax = L[1]
if firstMax > lastMax:
return firstMax
else:
return lastMax
else:
if isinstance(L[0], list):
firstMax = find_max(L[0])
lastMax = find_max(L[1:])
if firstMax > lastMax:
return firstMax
else:
return lastMax
else:
lastMax = find_max(L[1:])
if L[0] > lastMax:
return L[0]
else:
return lastMax