您可以通過使用一個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