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?
This will find the maximum in a list which contains nested lists and ignore string instances.
A = [2, 4, 6, 8, [[11, 585, "tu"], 100, [9, 7]], 5, 3, "ccc", 1]
def M(L):
# If list is empty, return nothing
if len(L) == 0:
return
# If the list size is one, it could be one element or a list
if len(L) == 1:
# If it's a list, get the maximum out of it
if isinstance(L[0], list):
return M(L[0])
# If it's a string, ignore it
if isinstance(L[0], str):
return
# Else return the value
else:
return L[0]
# If the list has more elements, find the maximum
else:
return max(M(L[:1]), M(L[1:]))
print A
print M(A)
Padmal's BLOG