Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polynomials as input in Python

How can you make Python take a polynomial as an input while maintaining the ability to substitute x for a real value?

Here is what I tried:

fx=input("Enter a Polynomial: ")
x=float(input("At which position should the polynomial be evaluated: "))

while True:
    print(eval("fx"))

    continue

The problem that arises is that Python will just evaluate fx as x and not as the value that I gave to x via my second input.

like image 527
Christian Singer Avatar asked Aug 31 '25 01:08

Christian Singer


2 Answers

This should help:

def eval_polynomial(poly, val):
    xs = [ x.strip().replace('^','**') for x in poly.split('+') ]
    return sum( [eval(n.replace('x', str(val))) for n in xs] )

Please keep in mind that you earlier have to make sure val is a number for safety reasons.

EDIT: more self-descriptive version as asked by Dipen Bakraniya

def fix_power_sign(equation):
    return equation.replace("^", "**")

def eval_polynomial(equation, x_value):
    fixed_equation = fix_power_sign(equation.strip())
    parts = fixed_equation.split("+")
    x_str_value = str(x_value)
    parts_with_values = (part.replace("x", x_str_value) for part in parts )
    partial_values = (eval(part) for part in parts_with_values)
    return sum(partial_values)
like image 129
Michał Avatar answered Sep 02 '25 14:09

Michał


Python 3

You can write:

fx = input("Enter a Polynomial: ")
x = float(input("At wich position should the polynomial be evaluated: "))

print(eval(fx.replace('x', str(x))))

Note: Above code will only work if you have entered polynomial in the form of *. For example: x**4 - x + 1

like image 41
Dipen Gajjar Avatar answered Sep 02 '25 13:09

Dipen Gajjar