您可以通过使用一个GCD例行寻找coprimes和治疗失败例外画出最奇数和偶数五角星代码相同的:
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()
对于从5到20的点,这只会找不到6的解决方案,您需要将其视为异常,即专用代码或让用户知道它是您无法处理的异常:
对于参数
> 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)
>
输出例如, '红色',10
我不认为有任何[常规星多边形(http://en.wikipedia.org/wiki/ Star_polygon#示例),边数少于5。 – martineau 2014-10-19 21:12:04
我知道没有,但像6,8,10等数字不符合上述公式。 – BryanLavinParmenter 2014-10-19 21:23:15
如果有偶数的边,你不需要两条断开的线? (把六角星看成两个三角形) – mdurant 2014-10-19 21:41:53