from turtle import*
from math import*
def Xcord(R,r,p,t):
x= (R-r) * cos(t) - (r+p) * cos((R-r)//r*t)
def Ycord (R,r,p,t):
y= (R-r) * sin(t) - (r+p) * sin((R-r)//r*t)
def t_iter(R,r,p):
t=0
down()
goto(Xcord(R,r,p,t),Ycord(R,r,p,t))
while (t < 2 * pi):
t = t+.01
Xcord(R,r,p,t)
Ycord(R,r,p,t)
up()
return
def main():
R=100
r=4
p=int(input("Please enter a number between 10 and 100: "))
if p < 10 or p > 100:
input(" Incorrect value of p!")
t_iter(R,r,p)
input("Hit enter to close porgram")
bye()
main()
I get this error:
Traceback (most recent call last):
File "C:/Users/Coscio/Desktop/spirals.py", line 31, in <module>
main()
File "C:/Users/Coscio/Desktop/spirals.py", line 27, in main
t_iter(R,r,p)
File "C:/Users/Coscio/Desktop/spirals.py", line 13, in t_iter
goto(Xcord(R,r,p,t),Ycord(R,r,p,t))
File "<string>", line 1, in goto
File "D:\Python\lib\turtle.py", line 1774, in goto
self._goto(Vec2D(*x))
TypeError: type object argument after * must be a sequence, not NoneType
from turtle import*
from math import*
def Xcord(R,r,p,t):
return (R-r) * cos(t) - (r+p) * cos((R-r)//r*t)
def Ycord (R,r,p,t):
return (R-r) * sin(t) - (r+p) * sin((R-r)//r*t)
def t_iter(R,r,p):
t=0
up()
Xcord(R,r,p,t)
Ycord(R,r,p,t)
while (t < 2 * pi):
t = t+.01
goto(Xcord(R,r,p,t),Ycord(R,r,p,t))
down()
return float(Xcord(R,r,p,t))
return float(Ycord(R,r,p,t))
def validate():
while True:
p=int(input("Please enter a number between 10 and 100: "))
if p >= 10 or p <= 100:
break
return p
def main():
speed(0)
R=100
r=4
p = validate()
t_iter(R,r,p)
Xcord(R,r,p,t_iter(R,r,p))
Ycord(R,r,p,t_iter(R,r,p))
input("Hit enter to close porgram")
bye()
main()
Related
I am creating an GUI for the wandrer game. After every two move of Hero, the characters move one tile as well.here I am trying to limited the movement of my characters(They cant move out of canvas and to the tiles which are wall) here is my code:
main.py
m = Map.matrix
def coords(char):
x, y = char.get_coordinates()
x, y = int(x / 72), int(y / 72)
return x, y
def leftKey(event):
if m[coords(hero)[1]][coords(hero)[0] - 1] != 1 and coords(hero)[0] > 0: # left
hero.move(x=-72)
hero.set_image(hero_left)
game.move_skeleton()
draw_canvas()
def rightKey(event):
if m[coords(hero)[1]][coords(hero)[0] + 1] != 1 and coords(hero)[0] <= 9: # right
hero.move(x=72)
hero.set_image(hero_right)
game.move_skeleton()
draw_canvas()
def upKey(event):
if m[coords(hero)[1] - 1][coords(hero)[0]] != 1 and coords(hero)[1] > 0: # up
hero.move(y=-72)
hero.set_image(hero_up)
game.move_skeleton()
draw_canvas()
def downKey(event):
if m[coords(hero)[1] + 1][coords(hero)[0]] != 1 and coords(hero)[1] <= 9: # down
hero.move(y=72)
hero.set_image(hero_down)
game.move_skeleton()
draw_canvas()
and here is game.py
def move_skeleton(self):
m = Map.matrix
if self.hero.count % 2 == 0 :
for char in self.characters:
movement= [[char.x -72, char.y],[char.x, char.y -72] ,[char.x +72, char.y],[char.x , char.y +72]]
good_movement = []
for neighbor in movement:
x , y = neighbor
if m[int(y/72)][int(x/72)] !=1 and y>=0 and y<9 * 72 and x >=0 and y<9*72:
good_movement.append(neighbor)
random_movement = good_movement[random.randint(0, len(good_movement)-1)]
char.x += random_movement[0]
char.y += random_movement[1]
when i run this code I get an error as below:
File "/Users/roxana/Desktop/WandererGame/main.py", line 91, in downKey
game.move_skeleton()
File "/Users/roxana/Desktop/WandererGame/game.py", line 96, in move_skeleton
if m[int(y/72)][int(x/72)] !=1 and y>=0 and y<9 * 72 and x >=0 and y<9*72:
IndexError: list index out of range
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
here is the my values in debbuger:
After a restart my script won't work anymore.
It worked before. Windows popping up, things needed to typed in and there was a result which I was happy with (like v0.9-alpha-happy). Now it yells at me.
import random
import tkinter as tk
from tkinter import simpledialog
from tkinter import messagebox
from tkinter import *
alleSpieler = []
team_eins = []
first_window = tk.Tk
first_window.withdraw()
def main():
global alleSpieler, i, x
i = 1
x = simpledialog.askinteger("Spieleranzahl", "Anzahl der Spieler: ")
if x % 2 == 0:
while i < x + 1:
spieler = simpledialog.askstring("Spielername", "Gib Spielername {} ein: ".format(i))
alleSpieler.append(spieler)
i = i + 1
else:
messagebox.showinfo("Nope", "Bitte gib eine gerade Anzahl von Spielern ein!")
main()
def sec():
j = 1
while j <= len(alleSpieler):
random_name = random.choice(alleSpieler)
team_eins.append(random_name)
alleSpieler.remove(random_name)
j = j + 1
def teams():
root = Tk()
t = Text(root)
for n in team_eins:
t.insert(END,"Team 1: " + n + "\n")
for n in alleSpieler:
t.insert(END,"Team 2: " + n + "\n")
t.pack()
root.mainloop()
main()
sec()
team1()
And the error(s):
/Users/benediktrautenberg/PycharmProjects/TeamGenerator/venv/bin/python /Users/benediktrautenberg/PycharmProjects/TeamGenerator/Generator.py
Traceback (most recent call last):
File "/Users/benediktrautenberg/PycharmProjects/TeamGenerator/Generator.py", line 48, in <module>
main()
File "/Users/benediktrautenberg/PycharmProjects/TeamGenerator/Generator.py", line 17, in main
x = simpledialog.askinteger("Spieleranzahl", "Anzahl der Spieler: ")
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/simpledialog.py", line 343, in askinteger
d = _QueryInteger(title, prompt, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/simpledialog.py", line 271, in __init__
Dialog.__init__(self, parent, title)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/simpledialog.py", line 137, in __init__
if parent.winfo_viewable():
AttributeError: 'NoneType' object has no attribute 'winfo_viewable'
Process finished with exit code 1
All I did to solve this error was:
first_window = Tk()
first_window.withdraw()
You forgot the () near Tk, so your not actually instantiating it properly.
I am trying to create an L-BFGS minimizing function for a initial guess of a symmetric matrix (to simplify taking the first hessian). The language I am using is python, and the library we are allowed to use is numpy. While there may be other errors I am as yet unaware of, I would like help solving a specific error where my random matrix A (nxn) is being interpreted as a 'str'. Thank you!
I have the following code:
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 16:33:22 2020
#author: 12064
"""
n = input("input the dimension of the function : ")
x_row = np.array(x)
x_column = np.transpose(x_row)
A = np.random.randn(n,n)
B = np.transpose(A)
f = np.matmul(B, A)
m = 5
k = 0
alpha = 1
epsilon = 10 ** -4
#define var's
gradf = np.gradient(f)
gradf_at_x = gradf.dot(x)
hessian_0 = np.gradient(gradf)
g[k] = gradf.dot(x[k])
condition_1 = g[k].dot(g[k])
p_T[k] = np.array(n)
p[k] = np.transpose(p_T)
#index an array
memory1 = np.linspace(change_g[k-m], change_g[k])#
memory2 = np.linspace(change_x[k-m], change_x[k])
memory3 = np.linspace(alpha[k-m], alpha[k])
memory4 = np.linspace(p[k-m], p[k])
memory5 = np.linspace(x[k-m], x[k+1])
memory6 = np.linspace(g[k-m], g[k])
def myminimizer(x, f):
if np.sqrt(condition_1) < epsilon:
#magnitude of the gradient (square root of dot product of grad f at x'k) <= epsilon (10^-4)
return x, k
else:
if k < 1:
p[k] = -1 * (hessian_0 * gradf_at_x)
else:
p = -1 * r
omega = f.dot(x[k] + alpha[k]*p[k])
while 1:
alpha = r * alpha
x[k+1] = x[k] + alpha[k] * p[k]
change_x = x[k+1] - x[k]
change_g = g[k+1] - g[k]
q[k] = g[k]
for i in range(k-m, k):
alpha[i] = p[i] * change_x_transpose * q[i]
q = q - alpha[i] * change_g[i]
r = H[k] * q
for i in range (k-m, k):
Beta[i] = p[i] * change_g_transpose[i] * r[i]
r = r + change_x * (alpha[i] - Beta[i]) #check that its Beta[i]
k += 1
if np.sqrt(condition_1) < epsilon:
#magnitude of the gradient (square root of dot product of grad f at x'k) <= epsilon (10^-4)
print ("x, k")
print ("x is your omtimizer of f")
else:
if k < 1:
p[k] = -1 * (hessian_0 * gradf_at_x)
else:
p = -1 * r
omega = f.dot(x[k] + alpha[k]*p[k])
while 1:
alpha = r * alpha
x[k+1] = x[k] + alpha[k] * p[k]
change_x = x[k+1] - x[k]
change_g = g[k+1] - g[k]
q[k] = g[k]
for i in range(k-m, k):
alpha[i] = p[i] * change_x_transpose * q[i]
q = q - alpha[i] * change_g[i]
r = H[k] * q
for i in range (k-m, k):
Beta[i] = p[i] * change_g_transpose[i] * r[i]
r = r + change_x * (alpha[i] - Beta[i]) #check that its Beta[i]
k += 1
#END CODE#
My error message is:
runfile('C:/Users/12064/Desktop/Duncan/assignments/ass 4 4realsies.py', wdir='C:/Users/12064/Desktop/Duncan/assignments')
input the dimension of the function : 10
Traceback (most recent call last):
File "<ipython-input-41-e748654944e8>", line 1, in <module>
runfile('C:/Users/12064/Desktop/Duncan/assignments/ass 4 4realsies.py', wdir='C:/Users/12064/Desktop/Duncan/assignments')
File "C:\Users\12064\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\12064\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/12064/Desktop/Duncan/assignments/ass 4 4realsies.py", line 11, in <module>
A = np.random.randn(n,n)
File "mtrand.pyx", line 1425, in mtrand.RandomState.randn
File "mtrand.pyx", line 1555, in mtrand.RandomState.standard_normal
File "mtrand.pyx", line 167, in mtrand.cont0_array
TypeError: 'str' object cannot be interpreted as an integer
Any directions on why the matrix I'm trying to create is causing this error would be greatly appreciated!
convert input string into integer:
n = int(input("input the dimension of the function : "))
I'm currently trying to write a program that gathers all resistors, calculates, then gets voltage and then calculates current. Here is what I have so far:
resistors = [0]
def ObtainResistors(resistors):
for i in range(1, 8):
value = int(input('please enter resistor %d:' % i))
resistors.append(value)
return
def TotalResistance(resistors):
rt1 = ((resistors[2] * resistors[3]) / (resistors[2] + resistors[3]))
print(rt1, 'ohms')
rt2 = (rt1 + resistors[4])
print(rt2, 'ohms')
rt3 = ((rt2 * resistors[5]) / (rt2 + resistors[5]))
print(rt3, 'ohms')
rt4 = (rt3 + resistors[7])
print(rt4, 'ohms')
rt5 = ((rt4 * resistors[6]) / (rt4 + resistors[6]))
print(rt5, 'ohms')
rt6 = (rt5 + resistors[1])
print(rt6, 'ohms')
rt = (rt1 + rt2 + rt3 + rt4 + rt5 + rt6)
print(rt, 'ohms')
return
ObtainResistors(resistors)
print(resistors)
TotalResistance(resistors)
print(resistors)
This is what i get when i run
please enter resistor 1:1
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/Introduction_to_Python/RESISTOR COURSEWORK.py", line 31, in <module>
TotalResistance(resistors)
File "C:/Users/User/PycharmProjects/Introduction_to_Python/RESISTOR COURSEWORK.py", line 12, in TotalResistance
rt1 = ((resistors[2] * resistors[3]) / (resistors[2] + resistors[3]))
IndexError: list index out of range
[0, 1]
Process finished with exit code 1
You are only reading 1 resistor value if you return in loop.
Move the return out of loop, or remove it since Python doesn't require explicit return and you're not returning a value:
def ObtainResistors(resistors):
for i in range(1, 8):
value = int(input('please enter resistor %d:' % i))
resistors.append(value)
# return
I'm unsure where I'm getting this error:
Traceback (most recent call last):
File "C:/Users/Coscio/PycharmProjects/unigram/letterHist.py", line 78, in <module>
main()
File "C:/Users/Coscio/PycharmProjects/unigram/letterHist.py", line 74, in main
bars(words)
File "C:/Users/Coscio/PycharmProjects/unigram/letterHist.py", line 62, in bars
init(words, lst)
File "C:/Users/Coscio/PycharmProjects/unigram/letterHist.py", line 38, in init
freqLegend(words,val, lst)
File "C:/Users/Coscio/PycharmProjects/unigram/letterHist.py", line 54, in freqLegend
freqLegend(words, val/1.5, counter-1)
File "C:/Users/Coscio/PycharmProjects/unigram/letterHist.py", line 53, in freqLegend
back((max(lst)*1000)/10)
TypeError: 'int' object is not iterable
I think its happening in my freqLegend function where I am taking the max of lst and dividing it by 10 but I'm not iterating through anything at this point and I cant find why I am getting this error.
from letterFreq import *
from turtle import *
def init(words, lst):
val = max(lst)
print(val)
speed(0)
setup (width=600, height=600, startx=0, starty=0)
up()
lt(180)
forward(200)
lt(90)
forward(100)
lt(90)
down()
forward(400)
up()
forward(-400)
lt(90)
down()
forward(val*1000)
up()
back(val*1000+20)
rt(90)
forward(200)
write("A B C D E F G H I J K L M N O P Q "
"R S T U V W X Y Z", True, align="center")
goto(-200,-100)
lt(90)
forward((val*1000)/2)
lt(90)
forward(60)
write("Frequency", True, align="center")
rt(90)
goto(-200,153)
freqLegend(words,val, lst)
def freqLegend(words, val, lst, counter = 10):
if counter == 0:
goto(-200,-100)
return
elif counter > 0:
up()
lt(90)
down()
forward(30)
write(round(val, 3 ))
back(30)
rt(90)
back((max(lst)*1000)/10)
freqLegend(words, val/1.5, counter-1)
def bars(words):
lstFreq = []
for letters in letterFreq(words):
lstFreq.append(letterFreq(words)[letters])
lst = lstFreq
init(words, lst)
for i in lst:
down()
forward(i*1000)
rt(90)
forward(14)
left(90)
back(i*1000)
def main():
filename = "data/very_short.csv"
words = readWordFile(filename)
bars(words)
input("enter to close")
if __name__ == '__main__':
main()
You're missing an argument to freqLegend, so you're getting behavior that you don't expect. You have only three arguments:
freqLegend(words, val/1.5, counter-1)
Where I think you mean
freqLegend(words, val/1.5, lst, counter-1)
And the reason that you are getting an error that it is not iterable is because max() actually iterates through the list. Due to the argument counter-1 being passed to the function as the argument lst, on the second call lst is an int, which it can't iterate through to find the maximum.