I am trying to make a function which return max from nested list?

后端 未结 6 1653
无人及你
无人及你 2021-01-24 08:48

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?

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-24 09:48

    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:

    def r_max (given_list):
        largest = given_list[0]
        while type(largest) == type([]):
            largest = largest[0]
    
        for element in given_list:
            if type(element) == type([]):
                # If the list is empty, skip
                if(len(elemnt) == 0)
                    next
                max_of_elem = r_max(element)
                if largest < max_of_elem:
                    largest = max_of_elem
            else:                           # element is not a list
                if largest < element:
                    largest = element
    
        return larges
    

    while your at it, you might want to assert len(given_list)>0 or something equivalent.

提交回复
热议问题