Python in place solution, got an "instance has no attribute '__getitem__' " error


  • 0
    M

    I have done an in place solution, and it works fine elsewhere. But it will get an " instance has no attribute 'getitem' " error in leetcode.

    My code:

    # Definition for an interval.
    # class Interval:
    #     def __init__(self, s=0, e=0):
    #         self.start = s
    #         self.end = e
    
    class Solution:
        # @param intervals, a list of Intervals
        # @param newInterval, a Interval
        # @return a list of Interval
        def insert(self, intervals, newInterval):
            if len(intervals) == 0:
                intervals.append(newInterval)
                return intervals
            i = 0
            while i < len(intervals):
                if newInterval[1] < intervals[i][0]:
                    intervals.insert(i, newInterval)
                    break
                if newInterval[1] <= intervals[i][1]:
                    intervals[i][0] = min(intervals[i][0], newInterval[0])
                    break
                if newInterval[0] <= intervals[i][1]:
                    newInterval[0] = min(intervals[i][0], newInterval[0])
                    intervals.remove(intervals[i])
                    continue
                i += 1
            return intervals
    

    The error I got:

    Runtime Error Message: Line 17: AttributeError: Interval instance has
    no attribute 'getitem' Last executed input: [[1,5]], [2,3]

    Does anyone have any clue? Thanks!


  • 1

    Did you read the definition of an Interval in the comment section above?

    I think you meant intervals[i].start for intervals[i][0] and intervals[i].end for intervals[i][1].

    Also, you could not compare two intervals directly:

    newInterval[1] < intervals[i][0]
    

    Did you mean to compare its attributes instead?


  • 0
    M
    This post is deleted!

Log in to reply
 

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