I Am Trying To Make A Function Which Return Max From Nested List?
Solution 1:
You are assuming given_list has at least 1 element which is incorrect. To avoid index out of range, you may add
if (len(given_list) == 0)
returnNone
to the beginning of your function.
Solution 2:
that error indicates your index is out of range, which is the case with the first element of your example. The solution is not to iterate over lists of length zero:
defr_max (given_list):
largest = given_list[0]
whiletype(largest) == type([]):
largest = largest[0]
for element in given_list:
iftype(element) == type([]):
# If the list is empty, skipif(len(elemnt) == 0)
next
max_of_elem = r_max(element)
if largest < max_of_elem:
largest = max_of_elem
else: # element is not a listif largest < element:
largest = element
return larges
while your at it, you might want to assert len(given_list)>0
or something equivalent.
Solution 3:
If the nesting is arbitrarily deep, you first need recursion to untangle it:
defitems(x):
ifisinstance(x, list):
for it in x:
for y in items(it): yield y
else: yield x
Now, max(items(whatever))
will work fine.
In recent releases of Python 3 you can make this more elegant by changing
foritin x:
foryinitems(x): yield y
into:
for it in x: yieldfrom it
Solution 4:
If you're confident that there will only be one level of nesting in there, you could do something like
defr_max(lst):
new_lst = []
for i in lst:
try:
new_lst.extend(i)
except TypeError:
new_lst + [i]
returnmax(new_lst)
But I'm not in love with that solution - but it might inspire you to come up with something nicer.
Two things I'd like to highlight about this solution, in contrast to yours:
- All the type-checking you're doing (
type(largest) == type([])
, etc.) isn't considered idiomatic Python. It works, but one of the key points of Python is that it promotes duck typing/EAFP, which means that you should be more concerned with what an object can do (as opposed to what type it is), and that you should just try stuff and recover as opposed to figuring out if you can do it. - Python has a perfectly good "find the largest number in a list" function -
max
. If you can make your input a non-nested list, thenmax
does the rest for you.
Solution 5:
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]
defM(L):
# If list is empty, return nothingiflen(L) == 0:
return# If the list size is one, it could be one element or a listiflen(L) == 1:
# If it's a list, get the maximum out of itifisinstance(L[0], list):
return M(L[0])
# If it's a string, ignore itifisinstance(L[0], str):
return# Else return the valueelse:
return L[0]
# If the list has more elements, find the maximumelse:
returnmax(M(L[:1]), M(L[1:]))
print A
print M(A)
Post a Comment for "I Am Trying To Make A Function Which Return Max From Nested List?"