Is there a way to simplify this function, in terms of less if statements and typing the same code over and over?
This function creates sine graphs based on the number the user requests. There is a lot of repeating code. I tried to use lists to store the objects, but get an error when trying to access them. How can I fix this?
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)
Here's a reimplementation that avoids the duplication and works for counts from 1 up, to the limit of EVEN_NUMBERS
and COLORS
:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.