Solving Monomial and Polynomial Python Class - python

I am experimenting with classes for the first time, and I wanted to create a program that asks the user for an input a,b, and c, and then solves for x for the equation forms stated in the print statements. However, I am having issues with the class, giving me an error that I am not using the variables in the class, missing the 5 positional arguments. Any help would be amazing, thanks so much.
class EquationSolver:
def MonomialSolver(self,a,b,c,x):
a = input("Enter Input for a:")
b = input("Enter Input for b:")
c = input("Enter input for c:")
x = (c+b)/a
print("For the equation in the format ax-b=c, with your values chosen x must equal", x)
def PolynomialSolver(self,a,b,c,x):
a = input("Enter Input for a:")
b = input("Enter Input for b:")
c = input("Enter input for c:")
x = (c^2 + b) / a
print("For the equation in the format sqrt(ax+b) = c, with your values chosen x must equal", x)
MonomialSolver()
PolynomialSolver()

The problem I see is the inputs for the functions. You do not need the self parameter or any other parameter. The functions should run outside the loop. The edited version should loop something like this:
class EquationSolver:
def MonomialSolver():
# Uses float() to turn input to a number
a = float(input("Enter Input for a:"))
b = float(input("Enter Input for b:"))
c = float(input("Enter input for c:"))
x = (c+b)/a
print("For the equation in the format ax-b=c, with your values chosen x must equal", x)
def PolynomialSolver():
a = float(input("Enter Input for a:"))
b = float(input("Enter Input for b:"))
c = float(input("Enter input for c:"))
x = (c^2 + b) / a
print("For the equation in the format sqrt(ax+b) = c, with your values chosen x must equal", x)
EquationSolver.MonomialSolver()
EquationSolver.PolynomialSolver()

Related

This Python code for quadratic equation isn't working

I'm trying to get the userinput for a,b,c using a function and it doesn't seems to work
import math
def equationroots():
try:
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
except ValueError:
print("Not a number!")
my = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(my))
quadratic = (-b + sqrt_val)/(2 * a)
return quadratic
print("The equation root of the numbers is" quadratic)
equationroots()
You have not used the proper intents, This is what your code supposed to be.
import math
def equationroots():
try:
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
except ValueError:
print("Not a number!")
my = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(my))
quadratic = (-b + sqrt_val)/(2 * a)
return quadratic
quadratic = equationroots()
print("The equation root of the numbers is", quadratic)
Indentation is very important in Python to separate block statements. It appears your indentation is off, leading to some lines not being executed when you intend.
For example, the variables my, sqrt_val, and quadratic are only calculated if the except label is reached. This means they are only attempted to be calculated if there is an input error, which wouldn't work anyways.
It's possible you also pasted in your code and the formatting was adjusted, and that isn't the issue. If that is the case, please edit the question to reflect the formatting and indentation you are using.
You need to fix your indentations from the except portion. Indentations are very important in python
fix this portion:
except ValueError:
print("Not a number!")
my = (b*b)-(4*a*c)
sqrt_val = math.sqrt(abs(my))
quadratic = ((-b)+sqrt_val)/(2*a)
return quadratic
then call your function first then use that to print your statement. Like,
quadratic = equationroots()
print(f"The equation root of the numbers is {quadratic}")

How to create a program to calculate a polynomial in python?

So this is the directions to my homework:
Write a program to calculate a polynomial. The program should ask for
the user for a,b,c, and x. It should ouput the value of ax^2+ bx +c by
calling a function named CalcPoly(a,b,c,x) that returns the value of
the function to the main program. The main program should print, not
the function.
And this is what I have so far:
def CalcPoly(a, b, c, x):
print ("Enter the first degree: ")
print (int(input(a)))
print ("Enter the second degree: ")
print (int(input(b)))
print ("Enter the third degree: ")
print (int(input(c)))
print (a*x**2 + b*x + c)
CalcPoly()
And the error I got was:
Traceback (most recent call last):
File "main.py", line 14, in <module>
CalcPoly()
TypeError: CalcPoly() missing 4 required positional arguments: 'a', 'b', 'c', and 'x'
I don't know how to fix it and I don't even know if I did the code right. I would appreciate any assistance. Thank you so much!
Try this:
def CalcPoly(a, b, c, x):
print (a*x**2 + b*x + c)
if __name__=="__main__":
a = int(input("Enter the first degree: "))
b = int(input("Enter the second degree: "))
c = int(input("Enter the third degree: "))
CalcPoly(a, b, c, 4) # x=4
# Console:
# Enter the first degree: 1
# Enter the second degree: 2
# Enter the third degree: 3
# 27
Since you say that the main program should print and not the function, you may try this.
def CalcPoly(a, b, c, x):
result = (a*x**2) + (b*x) + c
return result
a = int(input("Enter the coefficient of x^2 (a): "))
b = int(input("Enter the coefficient of x (b): "))
c = int(input("Enter the constant (c): "))
x = int(input("Enter x :"))
value = CalcPoly(a, b, c,x)
print(value)
Also you were facing an issue with your code, that is -
TypeError: CalcPoly() missing 4 required positional arguments: 'a', 'b', 'c', and 'x'
This is because while defining the CalcPoly() function you have declared 4 positional arguments a, b, c and x and while calling the function you haven't given the values of a, b, c and x in the function call.
The function CalcPoly expects the arguments of the polynomial coefficients and the value of variable x.
You can call the function correctly as follows:
CalcPoly(1,2,3,4)
This will evaluate the equation as x^2 + 2x + 3 where x=4.
But, if you are reading inputs, you must define function as follows:
def CalcPoly()
And also, please do not forget to read input for the value of x.
There are a lot of things wrong in your code.
First, the reason for the error itself-
def CalcPoly(a, b, c, x):
This takes in 4 arguments, a, b, c, and x, you pass none of them when calling the function-
CalcPoly()
Now, that is far from the end of the story. In python you take input like this-
a = int(input())
This gets user input and stores it into a. I'm assuming that's what you wanted to do, any argument within the parens of input() means that will be printed as a prompt-
a = int(input("Enter the first degree: "))
This will prompt the user,
Enter the first degree:
then wait for user input, turn it into an int and store it inside a
All the other input should be the same.
Your question says you should be taking input for a, b, c, and x, not just a, b, c.
So your fixed up function should look like-
def CalcPoly(a, b, c, x):
a = int(input("Enter the first degree: "))
b = int(input("Enter the second degree: "))
c = int(input("Enter the third degree: "))
x = int(input("Enter the x value: "))
print(a*x**2 + b*x + c)
This is really basic stuff, you should read the python docs tutorial
I'd like to add an object-oriented approach here. Let's create a class where the method get_input collects inputs from users and the method __call__ basically performs the polynomial calculation. This way you can separate the process of data collection and the actual calculation.
from typing import Union
class CalcPoly:
def get_input(self):
a: int = int(input("Enter the first degree:"))
b: int = int(input("Enter the second degree:"))
c: int = int(input("Enter the third degree:"))
x: Union[int, float] = input("Enter x:")
return a, b, c, x
def __call__(self):
a, b, c, x = self.get_input()
return (a*x**2) + (b*x) + c
calc = CalcPoly()
print(calc())

How do you divide a number by a number from a index?

My program is supposed to answer equations in the form ax = b
a = input("What is the part with the variable? ")
b = input("What is the answer? ")
print('the equation is', a , '=', b)
letter = a[-1]
number = a[0:-1]
answer = b /= number
print(letter,"=",answer)
In line 6, I'm getting an invalid syntax error. How can do it to answer the equation?
a = input("What is the part with the variable? ")
b = input("What is the answer? ")
print('the equation is', a , '=', b)
letter = a[-1]
number = a[0:-1]
answer =float(b)/float(number)
print(letter,"=",answer)
What is the part with the variable? 25c
What is the answer? 8
the equation is 25c = 8
c = 0.32
A quick solution. Note, you need to change the type of your input from string (I used float for this, but integer should also work).
a = float(input("What is the part with the variable? "))
b = float(input("What is the answer? "))
print('the equation is',a,'* X =',b)
# solve the equation: aX = b for X
x = b/a
print("X =",x)
This is a better version of you code :
a = input("What is the part with the variable? ")
b = input("What is the left hand side of the equation? ")
print('the equation is {}x = {}'.format(a , b))
answer = float(b) /float(a) // convert the inputs to floats so it can accept mathematical operations
print("x=",answer)

How to solve and equation with inputs in python [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
I am trying to create a python program that uses user input in an equation. When I run the program, it gives this error code, "answer = ((((A*10A)**2)(B*C))*D**E) TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'". My code is:
import cmath
A = input("Enter a number for A: ")
B = input("Enter a number for B: ")
C = input("Enter a number for C: ")
D = input("Enter a number for D: ")
E = input("Enter a number for E: ")
answer = ((((A*10**A)**2)**(B*C))*D**E)
print(answer)`
The input() function returns a string value: you need to convert to a number using Decimal:
from decimal import Decimal
A = Decimal(input("Enter a number for A: "))
# ... etc
But your user might enter something that isn't a decimal number, so you might want to do some checking:
from decimal import Decimal, InvalidOperation
def get_decimal_input(variableName):
x = None
while x is None:
try:
x = Decimal(input('Enter a number for ' + variableName + ': '))
except InvalidOperation:
print("That's not a number")
return x
A = get_decimal_input('A')
B = get_decimal_input('B')
C = get_decimal_input('C')
D = get_decimal_input('D')
E = get_decimal_input('E')
print((((A * 10 ** A) ** 2) ** (B * C)) * D ** E)
The compiler thinks your inputs are of string type. You can wrap each of A, B, C, D, E with float() to cast the input into float type, provided you're actually inputting numbers at the terminal. This way, you're taking powers of float numbers instead of strings, which python doesn't know how to handle.
A = float(input("Enter a number for A: "))
B = float(input("Enter a number for B: "))
C = float(input("Enter a number for C: "))
D = float(input("Enter a number for D: "))
E = float(input("Enter a number for E: "))
That code would run fine for python 2.7 I think you are using python 3.5+ so you have to cast the variable so this would become like this
import cmath
A = int(input("Enter a number for A: "))
B = int(input("Enter a number for B: "))
C = int(input("Enter a number for C: "))
D = int(input("Enter a number for D: "))
E = int(input("Enter a number for E: "))
answer = ((((A*10**A)**2)**(B*C))*D**E)
print(answer)
I tested it
Enter a number for A: 2
Enter a number for B: 2
Enter a number for C: 2
Enter a number for D: 2
Enter a number for E: 2
10240000000000000000
there are three ways to fix it, either
A = int(input("Enter a number for A: "))
B = int(input("Enter a number for B: "))
C = int(input("Enter a number for C: "))
D = int(input("Enter a number for D: "))
E = int(input("Enter a number for E: "))
which limits you to integers (whole numbers)
or:
A = float(input("Enter a number for A: "))
B = float(input("Enter a number for B: "))
C = float(input("Enter a number for C: "))
D = float(input("Enter a number for D: "))
E = float(input("Enter a number for E: "))
which limits you to float numbers (which have numbers on both sides of the decimal point, which can act a bit weird)
the third way is not as recommended as the other two, as I am not sure if it works in python 3.x but it is
A = num_input("Enter a number for A: ")
B = num_input("Enter a number for B: ")
C = num_input("Enter a number for C: ")
D = num_input("Enter a number for D: ")
E = num_input("Enter a number for E: ")
input() returns a string, you have to convert your inputs to integers (or floats, or decimals...) before you can use them in math equations. I'd suggest creating a separate function to wrap your inputs, e.g.:
def num_input(msg):
# you can also do some basic validation before returning the value
return int(input(msg)) # or float(...), or decimal.Decimal(...) ...
A = num_input("Enter a number for A: ")
B = num_input("Enter a number for B: ")
C = num_input("Enter a number for C: ")
D = num_input("Enter a number for D: ")
E = num_input("Enter a number for E: ")

python linear equation with Cramer's rule

I'm new to python and attempting to write a linear equation using Cramer's Rule. I've entered the formula and have code prompting user to enter a,b,c,d,e and f but my code is getting a syntax error. I'd like to fix the code and also have a system for researching and correcting future errors.
a,b,c,d,e,f = float(input("Enter amount: ")
a*x + by = e
cx + dy = f
x = ed-bf/ad-bc
y=af-ed/ad-bc
if (ad - bc == 0)print("The equation has no solution")
else print ("x=" x, "y=" y,)
Basically, your code was one giant syntax error. Please read some basic tutorial, as was suggested in the comments. Hopefully this will help in the learning process (I didn't go through the actual math formulas):
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
d = float(input("Enter d: "))
e = float(input("Enter e: "))
f = float(input("Enter f: "))
##a*x + by = e
##cx + dy = f
if (a*d - b*c == 0):
print("The equation has no solution")
else:
x = (e*d-b*f)/(a*d-b*c)
y = (a*f-e*d)/(a*d-b*c)
print ("x=%s" % x, "y=%s" % y)
You have to put * between the numbers you want to multiply. You had one parenthesis missing from your input statement. The equations themselves are commented out, because otherwise Python takes them as a code (incorrectly written one). You have to enclose the denominator in parentheses because math. You have to end the if, else, elif, for, while and such with :. Indentation is VERY important in Python.

Categories

Resources