<p>通过使用GCD例程查找coprimes并将失败视为异常,您可以使用相同的代码绘制大多数奇偶尖星:</p>
<pre><code>import sys
import turtle
from time import sleep
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def normal_star(size, color, points):
if points <= 4:
raise ValueError('Not enough points')
turtle.color(color)
for coprime in range(points // 2, 1, -1):
if gcd(points, coprime) == 1:
print("({},{})".format(points, coprime), file=sys.stderr)
start = turtle.position()
for _ in range(points):
turtle.forward(size)
turtle.left(360.0 / points * coprime)
turtle.setposition(start)
return
abnormal_star(size, color, points)
def abnormal_star(size, color, points):
# deal with special cases here
print("Exception:", points, file=sys.stderr)
for points in range(5, 20):
turtle.reset()
normal_star(200, 'red', points)
sleep(5)
turtle.exitonclick()
</code></pre>
<p>对于从5到20的点,这只是找不到6的解决方案,您需要将其视为异常,即专用代码或只是让用户知道这是您无法处理的异常:</p>
<pre><code>> python3 test.py
(5,2)
Exception: 6
(7,3)
(8,3)
(9,4)
(10,3)
(11,5)
(12,5)
(13,6)
(14,5)
(15,7)
(16,7)
(17,8)
(18,7)
(19,9)
(20,9)
>
</code></pre>
<p>参数200的输出示例,“red”,10</p>
<p><a href="https://i.stack.imgur.com/KCfoe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KCfoe.png" alt="enter image description here"/></a></p>