[英]Simplify Python Turtle plotting of similar functions
有沒有一種方法可以簡化此功能,減少if語句並一遍又一遍地鍵入相同的代碼?
此功能根據用戶請求的數量創建正弦圖。 有很多重復的代碼。 我試圖使用列表來存儲對象,但是在嘗試訪問它們時出現錯誤。 我怎樣才能解決這個問題?
def createWaves(amp, count):
even_num = [2, 4, 6, 8, 10, 12]
alpha = createTurtle("turtle", "darkcyan", 2)
alpha.ht()
beta = createTurtle("turtle", "purple", 2)
beta.ht()
gamma = createTurtle("turtle", "orange", 2)
gamma.ht()
delta = createTurtle("turtle", "magenta", 2)
delta.ht()
epsilon = createTurtle("turtle", "deepskyblue", 2)
epsilon.ht()
zeta = createTurtle("turtle", "green", 2)
zeta.ht()
omega = createTurtle("turtle", "black", 3)
omega.ht()
if count == 0:
alpha.st()
for x in range(361):
y_alpha = (amp/even_num[0]) *(math.sin(math.radians(x*even_num[0])))
alpha.goto(x, y_alpha)
elif count == 1:
alpha.st()
beta.st()
omega.st()
for x in range(361):
y_alpha = (amp/even_num[0]) *(math.sin(math.radians(x*even_num[0])))
y_beta = (amp/even_num[1]) *(math.sin(math.radians(x*even_num[1])))
y_omega = y_alpha + y_beta
alpha.goto(x, y_alpha)
beta.goto(x, y_beta)
omega.goto(x, y_omega)
elif count == 2:
alpha.st()
beta.st()
gamma.st()
omega.st()
for x in range(361):
y_alpha = (amp/even_num[0]) *(math.sin(math.radians(x*even_num[0])))
y_beta = (amp/even_num[1]) *(math.sin(math.radians(x*even_num[1])))
y_gamma = (amp/even_num[2]) *(math.sin(math.radians(x*even_num[2])))
y_omega = y_alpha + y_beta + y_gamma
alpha.goto(x, y_alpha)
beta.goto(x, y_beta)
gamma.goto(x, y_gamma)
omega.goto(x, y_omega)
這是一個重新實現,它避免了重復,並且適用於從1到EVEN_NUMBERS
和COLORS
的限制的EVEN_NUMBERS
:
import math
from turtle import Turtle, Screen
EVEN_NUMBERS = [2, 4, 6, 8, 10, 12]
COLORS = ["darkcyan", "purple", "orange", "magenta", "deepskyblue", "green", "black"]
def createWaves(amp, count):
screen.tracer(False)
for x in range(361):
y_offsets = []
for i in range(count):
turtles[i].showturtle()
y_offset = math.sin(math.radians(x * EVEN_NUMBERS[i])) * amp / EVEN_NUMBERS[i]
turtles[i].goto(x, y_offset)
y_offsets.append(y_offset)
if count > 1:
turtles[-1].showturtle()
turtles[-1].goto(x, sum(y_offsets))
screen.update()
screen.tracer(True)
screen = Screen()
turtles = []
for color in COLORS:
turtle = Turtle("turtle", visible=False)
turtle.speed('fastest')
turtle.color(color)
turtle.width(2)
turtles.append(turtle)
turtles[-1].width(3) # summation turtle
createWaves(100, 4)
screen.exitonclick()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.