合并重叠间隔会产生AttributeError

时间:2018-05-05 18:26:16

标签: python merge

  

给定一系列间隔,合并所有重叠的间隔。

     

例如:

     

给定[1,3],[2,6],[8,10],[15,18]

     

返回[1,6],[8,10],[15,18]

     

确保已返回的间隔已排序。

class Solution:
    # @param intervals, a list of Intervals
    # @return a list of Interval
    def merge(self, intervals):
        A = intervals
        A.sort(key=lambda x: x.start)
        N = len(A)
        S = []
        if A:
            S.append(A[0])
            for i in range(1, N):
                B = A[i]
                if B.start <= S[-1].end:
                    S[-1].end = max(S[-1].end, B.end)
                else:
                    S.append(B)
        return S

X=[[1,3],[2,6],[8,10],[15,18]]
sol=Solution()
print(sol.merge(X))

编译后我收到错误:

  File "main.py", line 24, in <module>
    print(sol.merge(X))
  File "main.py", line 8, in merge
    A.sort(key=lambda x: x.start)
  File "main.py", line 8, in <lambda>
    A.sort(key=lambda x: x.start)
AttributeError: 'list' object has no attribute 'start'

但该解决方案已被 Interviewbit 接受。

1 个答案:

答案 0 :(得分:0)

只需实现一个最小$result | Select-Object -First $(result.Count-1)类即可正常运行代码:

Interval

或者您可以使用class Interval: def __init__(self, start, end): self.start, self.end = start, end def __repr__(self): return str([self.start, self.end]) 获得大致相同的内容:

namedtuple

并将from collections import namedtuple Interval = namedtuple('Interval', ('start', 'end')) 转换为使用X s:

Interval