А обязательно все руками писать?
Может можно:
from sympy.parsing.sympy_parser import parse_expr
expression = "-2+x^1-3*x^2+x^2+100*x^3-2*x"
x = 0
formula = expression.replace('x', str(x)).replace('^', '**')
print(parse_expr(formula))
На выходе:
−2
Еще можно так сделать:
from sympy import symbols
from sympy.parsing.sympy_parser import parse_expr
expression = "-2+x^1-3*x^2+x^2+100*x^3-2*x"
x = symbols('x')
formula = parse_expr(expression.replace('^', '**'), local_dict={'x': x})
print('Формула:', formula)
for i in range(3):
y = formula.subs(x, i)
print(f'x={i}', f'y={y}')
Результат:
Формула: 100*x**3 - 2*x**2 - x - 2
x=0 y=-2
x=1 y=95
x=2 y=788
Ну вот тогда интересненький, на мой взгляд, способ:
from functools import reduce
expression = "-2+x^1-3*x^2+x^2+100*x^3-2*x"
x = 0
expression = 'x*x^3*3+3^3+1^5*4'
x = 2
class Pow:
_symbol = '^'
_action = '__pow__'
def __init__(self, expr):
self._expr = expr
if self.__class__.__base__ is not object:
self._parent = self.__class__.__base__
else:
self._parent = int
def __repr__(self):
return f'{self.__class__.__name__}({self._symbol}, {self._expr})'
def __str__(self):
return '{}({}, {} = {})'.format(
self.__class__.__name__,
self._symbol,
self._expr,
str(self.__int__()))
def __int__(self):
split = self._expr.split(self._symbol)
if len(split) > 1:
return reduce(self._calc, [self._parent(i) for i in split])
else:
return int(self._parent(split[0]))
def _calc(self, x, y):
return getattr(int(x), self._action)(int(y))
class Mul(Pow):
_symbol = '*'
_action = '__mul__'
class Add(Mul):
_symbol = '+'
_action = '__add__'
print(Add(
expression.replace('x', str(x))
))
Результат:
79
Класс для вычитания сам напишешь?
А еще можно int
перегрузить: (обрати внимание на наличие минусов в expression
, на перегрузку __pow__
)
from functools import reduce
import logging
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
log.propagate = True
expression = "---2-x^1-3*x^2--x^2*2+100*x^3-2*x-3^x"
expression = '-2+x^1-3*x^2+x^2+100*x^3-2*x'
#expression = '-2+1^1-3^x'
x = -2
class Int(int):
def __new__(cls, expr):
"""Для решения проблемы отрицательного x"""
if isinstance(expr, str):
expr = expr.replace('--', '+')
return super().__new__(cls, expr)
def __pow__(self, y):
"""Для решения проблемы: assert (-3).__pow__(2) == 9"""
value = super().__pow__(y)
if self < 0 and value > 0:
value *= -1
log.debug('%s(%s ^ %s = %s)', self.__class__.__name__, self, y, value)
return value
class Pow(Int):
_symbol = '^'
def __new__(cls, expr):
action = '__{}__'.format(cls.__name__.lower())
parent = cls.__base__
if expr == '':
log.debug('%s(%s = %s)', cls.__name__, expr, 0)
return super().__new__(cls, 0)
split = expr.split(cls._symbol)
if len(split) > 1:
value = reduce(lambda x, y: getattr(x, action)(y),
[parent(i) for i in split])
log.debug('%s_calc(%s = %s)', cls.__name__, expr, value)
else:
value = parent(split[0])
log.debug('%s_get(%s = %s)', cls.__name__, expr, value)
log.debug('%s(%s = %s)', cls.__name__, expr, value)
return super().__new__(cls, value)
class Mul(Pow):
_symbol = '*'
class Add(Mul):
_symbol = '+'
class Calc(int):
_x_sym = 'x'
_parent = Add
def __new__(cls, expr, x):
while '--' in expr:
expr = expr.replace('--', '+')
expr = expr.replace('-', '+-')
expr = expr.replace(cls._x_sym, str(x))
value = cls._parent(expr)
log.debug('%s(%s = %s)', cls.__name__, expr, value)
return super().__new__(cls, value)
log.debug('(expr=%s) (x=%s)', expression, x)
print(Calc(expression, x))
Результат: -792
Вывод лога (для понимания хронологии событий):
DEBUG:__main__:(expr=---2-x^1-3*x^2--x^2*2+100*x^3-2*x-3^x) (x=2)
DEBUG:__main__:Mul( = 0)
DEBUG:__main__:Mul( = 0)
DEBUG:__main__:Pow_get(-2 = -2)
DEBUG:__main__:Pow(-2 = -2)
DEBUG:__main__:Mul_get(-2 = -2)
DEBUG:__main__:Mul(-2 = -2)
DEBUG:__main__:Int(-2 ^ 1 = -2)
DEBUG:__main__:Pow_calc(-2^1 = -2)
DEBUG:__main__:Pow(-2^1 = -2)
DEBUG:__main__:Mul_get(-2^1 = -2)
DEBUG:__main__:Mul(-2^1 = -2)
DEBUG:__main__:Pow_get(-3 = -3)
DEBUG:__main__:Pow(-3 = -3)
DEBUG:__main__:Int(2 ^ 2 = 4)
DEBUG:__main__:Pow_calc(2^2 = 4)
DEBUG:__main__:Pow(2^2 = 4)
DEBUG:__main__:Mul_calc(-3*2^2 = -12)
DEBUG:__main__:Mul(-3*2^2 = -12)
DEBUG:__main__:Int(2 ^ 2 = 4)
DEBUG:__main__:Pow_calc(2^2 = 4)
DEBUG:__main__:Pow(2^2 = 4)
DEBUG:__main__:Pow_get(2 = 2)
DEBUG:__main__:Pow(2 = 2)
DEBUG:__main__:Mul_calc(2^2*2 = 8)
DEBUG:__main__:Mul(2^2*2 = 8)
DEBUG:__main__:Pow_get(100 = 100)
DEBUG:__main__:Pow(100 = 100)
DEBUG:__main__:Int(2 ^ 3 = 8)
DEBUG:__main__:Pow_calc(2^3 = 8)
DEBUG:__main__:Pow(2^3 = 8)
DEBUG:__main__:Mul_calc(100*2^3 = 800)
DEBUG:__main__:Mul(100*2^3 = 800)
DEBUG:__main__:Pow_get(-2 = -2)
DEBUG:__main__:Pow(-2 = -2)
DEBUG:__main__:Pow_get(2 = 2)
DEBUG:__main__:Pow(2 = 2)
DEBUG:__main__:Mul_calc(-2*2 = -4)
DEBUG:__main__:Mul(-2*2 = -4)
DEBUG:__main__:Int(-3 ^ 2 = -9)
DEBUG:__main__:Pow_calc(-3^2 = -9)
DEBUG:__main__:Pow(-3^2 = -9)
DEBUG:__main__:Mul_get(-3^2 = -9)
DEBUG:__main__:Mul(-3^2 = -9)
DEBUG:__main__:Add_calc(++-2+-2^1+-3*2^2+2^2*2+100*2^3+-2*2+-3^2 = 779)
DEBUG:__main__:Add(++-2+-2^1+-3*2^2+2^2*2+100*2^3+-2*2+-3^2 = 779)
DEBUG:__main__:Calc(++-2+-2^1+-3*2^2+2^2*2+100*2^3+-2*2+-3^2 = 779)