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

后端 未结 6 1656
无人及你
无人及你 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:27

    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
    

提交回复
热议问题