1x1 正方形中的 Python 圆不重叠或位于正方形之外

问题描述 投票:0回答:1

我必须创建 50 个不重叠或位于正方形 (0,0) 到 (1,1) 之外的圆圈,这是迄今为止我的代码:

fig = plt.figure()
ax = fig.add_axes([.1, .1, .8, .8], axisbg = 'Violet', aspect = 'equal')
clist = []

def overlap(c1, c2):
    distance = ((c1.center[0] - c2.center[0])**2 + (c1.center[0] - c2.center[0])**2)**0.5
    return distance < c1.radius + c2.radius

for i in range(1000):
    x = np.random.rand(1)
    y = np.random.rand(1)
    c = Circle(xy=(x, y), radius = 0.05, fc = 'Blue', ec = 'DarkBlue', lw = 1.5)
    if x - 0.05 >= 0.0:
        if x + 0.05 <= 1.0:
            if y - 0.05 >= 0.0:
                if y + 0.05 <= 1.0:
                    if len(clist) == 0:
                        clist.append(c)
                        ax.add_patch(c)
                    else:
                        for j in range(len(clist)):
                            if overlap(c, clist[j]) == True:
                                break
                            if j == len(clist) - 1:
                                if overlap(c, clist) == False:
                                    clist.append(c)
                                    ax.add_atch(c)
    if len(clist) == 50:
        break
    
ax.autoscale()

如果我打印我的清单,我会得到以下信息:

[<matplotlib.patches.Circle object at 0x07E5F3D0>]

因此,当我运行代码时,会发生此错误:

 AttributeError                            Traceback (most recent call last)
 <ipython-input-35-48e3a2854e8e> in <module>()
     24                                 break
     25                             if j == len(clist) - 1:
---> 26                                 if overlap(c, clist) == False:
     27                                     clist.append(c)
     28                                     ax.add_atch(c)

<ipython-input-35-48e3a2854e8e> in overlap(c1, c2)
      4 
      5 def overlap(c1, c2):
----> 6     distance = ((c1.center[0] - c2.center[0])**2 + (c1.center[0] -     c2.center[0])**2)**0.5
      7     return distance < c1.radius + c2.radius
      8 

AttributeError: 'list' object has no attribute 'center'

所以错误在于圆被正确存储在列表中,但我见过其他人这样做。我做错了什么?

python python-3.x
1个回答
1
投票

您正在使用以下代码将

c
创建为
Circle

c = Circle(xy=(x, y), radius = 0.05, fc = 'Blue', ec = 'DarkBlue', lw = 1.5)

您最终将使用

clist
:

执行此代码
clist.append(c)

显然,一个是圆,另一个是列表。

您稍后执行此代码:

if overlap(c, clist[j]) == True:

显示

clist[j]
是一个圆圈,正如预期的那样。

然后,你这样做:

if overlap(c, clist) == False:

你不能那样做。

clist
是一个列表,而不是
Circle
。您必须对其进行索引,例如
clist[j]
或其他。

© www.soinside.com 2019 - 2024. All rights reserved.