矩形数组中的公共点

时间:2015-12-07 00:13:31

标签: python class loops oop

我正在创建一个涉及矩形类的程序,以及一个point和canvas类。我们要求的一个较小的函数是一个公共点函数,它确定手头的画布是否在整个矩形阵列中有一个共同点。我收到列表索引错误,但我看不出原因。

这是常用的点功能:

def common_point(self):
    '''(Rectangle) -> Boolean
    Returns True if rectangles in canvas all ahare a common point'''
    common = False
    for i in range(len(self.data)):
        for j in range(len(self.data),-1,-1):
            if self.data[i].intersects(self.data[j]) == True:
                common = True
            else:
                return False
    return common

这是它正在调用的交叉函数:

def intersects(self,other):
    '''(Rectangle, Rectangle) -> Boolean
    Returns True if the two Rectangles intersect'''
    return not(self.p2.y < other.p1.y or self.p1.y > other.p2.y or self.p2.x < other.p1.x or self.p1.x > other.p2.x)

任何帮助,为什么会非常感激

1 个答案:

答案 0 :(得分:1)

range(len(self.data),-1,-1)会返回长度为len(self.data) + 1的列表。当使用该范围进行迭代时,这将始终导致索引错误。

我怀疑你想要的是:

for j in range(len(self.data) - 1, -1, -1):