gpt4 book ai didi

python - 使用Python通过 turtle 引用列表或字典绘制正弦波

转载 作者:太空宇宙 更新时间:2023-11-03 14:07:35 25 4
gpt4 key购买 nike

我尝试从字典中提取字符串,并想在波函数中迭代它们。 turtle 应该用 x 和 y 的值发出正弦波。我也尝试过使用列表,但这没有用。也许这是不可能的,而且我对这个问题的理解完全错误。

import turtle, math

def createTurtle(count):
for x in range(count):
turtle_dict[x] = turtle.Turtle()
turtle_dict[x].shape("turtle")
turtle_dict[x].color(color_list[x])
turtle_dict[x].width(3)
return turtle_dict[x]

def wave(count):
for n in range(count):
amp = amp_list[n]
freq = freq_list[n]
createTurtle(n)
for x in range(361):
y_val = amp * math.sin(math.radians(x * freq))
turtle_dict.values().goto(x, y_val)
print(x, y_val)

num_waves = int(input("How many sine waves do you want to create? "))
amp_list = []
freq_list = []
turtle_dict = {1 : "alpha", 2 : "beta", 3 : "gamma", 4 : "delta", 5 : "omega"}
color_list = ["red", "blue", "green", "purple", "pink"]
counter = 1

for x in range(num_waves):
print("\nSine Wave #" , counter)
amp = int(input("Enter the amplitude of the sine wave: "))
freq = float(input("Enter the frequency of the sine wave: "))
amp_list.append(amp)
freq_list.append(freq)
counter += 1

print(amp_list)
print(freq_list)
print(turtle_dict)

amp_screen = max(amp_list) + 1

win = turtle.Screen()
win.bgcolor("lightyellow")
win.setworldcoordinates(0,-amp_screen, 500 ,amp_screen)

wave(counter-1)

win.exitonclick()

最佳答案

我的分析是你可以用一个列表来做到这一点——你不需要字典——它不起作用的原因是你的代码有很多错误。例如,createTurtle() 存在缩进错误,导致其过早返回。并且它的调用不正确,传递的是循环计数器而不是循环范围。 turtle_dict 未正确使用,对 turtle 列表 (.values()) 而不是单个 turtle 调用 goto()

这是我修复发现的问题并调整代码风格的返工:

import math
from turtle import Turtle, Screen
from itertools import cycle

color_list = ['red', 'blue', 'green', 'purple', 'pink']

def createTurtles(count):
turtles = []
colors = cycle(color_list)

for _ in range(count):
turtle = Turtle('turtle')
turtle.color(next(colors))
turtle.speed('fastest')
turtle.width(3)

turtles.append(turtle)

return turtles

def wave(count):
for n in range(count):
amp = amp_list[n]
freq = freq_list[n]
turtle = turtles_list[n]
turtle.penup()

for x in range(361):
y_val = amp * math.sin(math.radians(x * freq))
turtle.goto(x, y_val)
turtle.pendown()

num_waves = int(input('How many sine waves do you want to create? '))

amp_list = []
freq_list = []
counter = 1

for x in range(num_waves):
print('\nSine Wave #', counter)
amp = int(input('Enter the amplitude of the sine wave: '))
freq = float(input('Enter the frequency of the sine wave: '))
amp_list.append(amp)
freq_list.append(freq)
counter += 1

amp_screen = max(amp_list) + 1

screen = Screen()
screen.bgcolor('lightyellow')
screen.setworldcoordinates(0, -amp_screen, 400, amp_screen)

turtles_list = createTurtles(num_waves)

wave(counter - 1)

screen.exitonclick()

enter image description here

关于python - 使用Python通过 turtle 引用列表或字典绘制正弦波,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48760619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com