I tried turning the variable that I get from input(which is (x,y,z) as ints) into a tuple and a list successfully, but I cant seem to get the Polynomial()
to work with them.
from tkinter import *
class Polynomial:
def __init__(self, *coefficients):
self.coefficients = list(coefficients)
def __repr__(self):
return "Polynomial" + str(self.coefficients)
def __call__(self, x):
res = 0
for index, coeff in enumerate(self.coefficients[::-1]):
res += coeff * x ** index
return res
def calculateIt():
mathCoef = E1.get()
botch = mathCoef
mytuple = tuple(map(int, botch.split(',')))
p = Polynomial(mytuple)
for x in range(-3, 3):
print(x, p(x))
L1.configure(text=p)
print(mathCoef)
window = Tk()
window.title("XImath Client 1.0")
window.configure(bg="black")
window.geometry("500x500")
L1 = Label(window, text="Input")
L1.pack()
E1 = Entry(window, bd=5)
E1.pack()
B1 = Button(window, text="go", command=calculateIt)
B1.pack()
window.mainloop()
The problem is that I want the class(Polynomial)
to work with the variables given by user input in mathCoef
, which is a string at first. I tried turning into a tuple successfully, but class(Polynomial)
expects ints with this syntax - (1, 2, 3)
. Let's say the user inputs 1,2,3 - the tuple looks exactly like this - (1, 2, 3)
, but when I try passing it into Polynomial(mytuple)
, it returns:
TypeError: unsupported operand type(s) for +=: 'int' and 'tuple'
How do I turn the tuple into ints separated with commas?
Try the below code.
I believe what you may have been missing is the * in the line p = Polynomial(*coeffs)
which tells python to unpack the list as arguments that is passes to the constructor of the class.
I've also added repr(p)
to the line that adds the polynomial to the label, this will show you the repr string for that polynomial.
from tkinter import *
class Polynomial:
def __init__(self, *coefficients):
self.coefficients = list(coefficients)
def __repr__(self):
return "Polynomial" + str(self.coefficients)
def __call__(self, x):
res = 0
for index, coeff in enumerate(self.coefficients[::-1]):
res += coeff * x ** index
return res
def calculateIt():
mathCoef = E1.get()
coeffs = map(int, mathCoef.split(' '))
p = Polynomial(*coeffs)
for x in range(-3, 3):
print(x, p(x))
L1.configure(text=repr(p))
print(mathCoef)
window = Tk()
window.title("XImath Client 1.0")
window.configure(bg="black")
window.geometry("500x500")
L1 = Label(window, text="Input")
L1.pack()
E1 = Entry(window, bd=5)
E1.pack()
B1 = Button(window, text="go", command=calculateIt)
B1.pack()
window.mainloop()