【发布时间】:2016-06-01 19:09:28
【问题描述】:
所以我在练习 python 时遇到了这个问题,但我想它适用于所有语言。我要在规则的 n 边形中绘制所有对角线,这很好,我设法做到了。但是,还有另一个标准,同一条线不得多次绘制。我对此的解释是乌龟(顺便说一句我使用乌龟图形)不能在相同的两个角之间移动两次,而不仅仅是你要抬起笔。我也一直在尝试找到解决方案一段时间,但我似乎无法弄清楚并且开始怀疑它是否可能。
这里有人知道是否可以为所有 n 边形做吗?如果是的话,你能给我一个提示吗?
对于那些不知道那是什么的人来说,这里有两个常规的 n 边形。 (我肯定没有)
/问
编辑
感谢 John Kahn,我能够完成可解部分,正如他指出的那样,它只能在不均匀度数的规则 n 边形上完成。 这是我的解决方案的代码。你怎么看?
def nhorning(r, n, ):
if n % 2 == 0:
print("It can't be done")
return None
angl = (2 * pi) / n # angle for calculating all the coordinates of the n-gon
a = {} # contains the destinations for each corners diagonals
cord = {} # contains the coordinates of each corner
for x in range(n):
cord[x] = [float("%.2f" % (r * cos(x * angl))), float("%.2f" % (r * sin(x * angl)))] # all corners coordinates
for i in range(n): # the diagonals that are to be drawn from the corner "i"
a[i] = [x for x in range(n)]
a[i].remove(i) # can't draw a diagonal to itself
count = 0
pu()
goto(cord[0]) # you have to start on a corner
pd()
cordstring = str(cord) # a list isn't hashable, so making the lists to a string
while count < (((n-1) * n) / 2): # loops until all diagonals are drawn
if str(list(pos())) in cordstring: # should always be on the circles radius except in the beginning
for i in range(len(cord)):
if cord[i] == list(pos()): # finds what corner the turtle is on
where = i
diags = a[where] # the diagonals not drawn from the corner
dest = diags.pop() # the corner to which a diagonal is to be drawn,
# removes it since the diagonal to that corner will be drawn
nwhere = a[dest] # the diagonals not drawn from the corner where a
# diagonal is to be drawn next
nwhere.remove(where) # the diagonal from the destination corner to the current corner will be drawn next,
# so can't be drawn again
goto(cord[dest]) # draw the diagonal
count += 1
done()
【问题讨论】:
标签: math optimization polygon