Elegant python code without any case discussion


  • 0
    Z
    def findMissingRanges(self, nums, lower, upper):
            def to_range(l,r):#inclusive
                if l>r:
                    return None
                elif l==r:
                    return str(r)
                else:
                    return str(l)+'->'+str(r)
            def add_range(res,ran):
                if ran is not None:
                    res.append(ran)
            #add head
            res = []
            nums = [lower-1]+nums+[upper+1]
            n = len(nums)
            for i in range(n-1):
                l = nums[i]+1
                r = nums[i+1]-1
                ran = to_range(l,r)
                add_range(res,ran)
    
            return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.