我正在编写一个函数,在以原点为中心的圆的圆周上点等距点,然后在所有点之间画线。
我已经弄乱这段代码一段时间了,但我似乎无法让它按预期运行。我需要用给定半径的点和 turtle 中的点数做一个圆。这是我目前所拥有的:
from turtle import *
def drawLineSeg (p, q):
up()
goto(p)
down()
goto(q)
def pntCirc (r, n):
for i in range(1, n+1):
up()
goto(0,0)
forward(r)
down()
dot(10)
L.append (pos())
right(360/n)
L = []
def clique (r, n):
pntCirc (r, n)
color ('blue')
for i in range(0, len(L)):
drawLineSeg (L[0], L[i])
drawLineSeg (L[1], L[i])
drawLineSeg (L[2], L[i])
drawLineSeg (L[3], L[i])
drawLineSeg (L[4], L[i])
drawLineSeg (L[5], L[i])
drawLineSeg (L[6], L[i])
drawLineSeg (L[7], L[i])
drawLineSeg (L[8], L[i])
drawLineSeg (L[9], L[i])
drawLineSeg (L[10], L[i])
drawLineSeg (L[11], L[i])
drawLineSeg (L[12], L[i])
drawLineSeg (L[13], L[i])
drawLineSeg (L[14], L[i])
drawLineSeg (L[15], L[i])
drawLineSeg (L[16], L[i])
drawLineSeg (L[17], L[i])
drawLineSeg (L[18], L[i])
drawLineSeg (L[19], L[i])
return
speed(50)
color ('red')
clique (300, 20)
# clique (300, 8)
# clique (300, 16)
hideturtle()
done()
在 clique 函数中,我尝试使用 for
循环和 while 循环,这是我需要使用的循环;我不能再使用任何技术性的东西,例如 enumerate
、numpy
或 matplotlib
。我需要针对任意数量的给定点进行这项工作,而不仅仅是我测试的 20 点。例如,当我测试 8 个点时,它会抛出一个 IndexError
。我如何使用一段代码而不是硬写的代码来做到这一点?
clique (300, 20)
# clique (300, 8)
# clique (300, 16)
如上所述,我已经对其进行了硬编码,以便在使用 20 点时给出完整的结果 ( this is the full model that I hard coded the function for ),但是如果我只是输入:
for i in range(0, len(L)):
drawLineSeg (L[0], L[i])
任何帮助将不胜感激,因为我目前陷入困境并且不确定如何从这里继续。
最佳答案
这里很努力。你画的是 complete graph .你非常接近,只是缺少一个内部循环,它本质上是硬编码 20 调用所模拟的。
我们需要找到点的所有组合,所以逻辑本质上是一个嵌套循环:
for each point at index i from 0 to length(points):
for each other point from index i + 1 to length(points):
draw a line between the two points
虽然从中心移动 turtle 会起作用,但我更愿意用数学方法计算圆周周围的点。一个点的公式是:
x = math.cos(angle_in_radians) * radius + center_x
y = math.sin(angle_in_radians) * radius + center_y
...但出于我们的目的,假设中心为 0(这是制作参数的好事)。
为了计算圆周上的所有点,我们可以从 0 度到 360 度以 360/n(我们要绘制的点数)为增量进行迭代,然后将角度转换为弧度并代入公式。无需列表。
除此之外,我更愿意避免 from turtle import *
将太多函数引入命名空间。最好是 import turtle
,然后继续使用 turtle
前缀。我还希望创建一个 Turtle
实例并将其传递给函数,这样它就不会依赖于全局状态。
我也更喜欢在所有可用旋钮的功能上使用参数。中心 x
和 y
最好添加。
最后的结果是:
import math
import turtle
def clique(t, r, n, dotsize=10, dotcolor="red", linecolor="blue"):
for i in range(n):
a = 360 / n * i
x = math.cos(math.radians(a)) * r
y = math.sin(math.radians(a)) * r
t.color(linecolor)
for i in range(i + 1, n):
a = 360 / n * i
xx = math.cos(math.radians(a)) * r
yy = math.sin(math.radians(a)) * r
t.goto(x, y)
t.pendown()
t.goto(xx, yy)
t.penup()
t.goto(x, y)
t.color(dotcolor)
t.dot(dotsize)
if __name__ == "__main__":
t = turtle.Turtle()
t.penup()
t.speed("fastest")
clique(t, 200, 7)
turtle.exitonclick()
关于python - 用Turtle绘制圆周上等距点的完整图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64364662/