OPERATORS = {'+': (1, lambda x, y: x + y), '-': (1, lambda x, y: x - y), '*': (2, lambda x, y: x * y), '/': (2, lambda x, y: x / y), 'x': (2, lambda x, y: x * y),'^': (2, lambda x, y: x ** y)} 

last two operators

 def eval_(formula): def parse(formula_string): number = '' for s in formula_string: if s in '1234567890.': number += s elif number: yield float(number) number = '' if s in OPERATORS or s in "()": yield s if number: yield float(number) def shunting_yard(parsed_formula): stack = [] for token in parsed_formula: if token in OPERATORS: while stack and stack[-1] != "(" and OPERATORS[token][0] <= OPERATORS[stack[-1]][0]: yield stack.pop() stack.append(token) elif token == ")": while stack: x = stack.pop() if x == "(": break yield x elif token == "(": stack.append(token) else: yield token while stack: yield stack.pop() def calc(polish): stack = [] for token in polish: if token in OPERATORS: y, x = stack.pop(), stack.pop() stack.append(OPERATORS[token][1](x, y)) else: stack.append(token) return stack[0] return calc(shunting_yard(parse(formula))) 

in the dictionary, operators of 5 pieces when used in formulas work fine, '**', '+', '/', '-', '*' for example

print (eval ("2 ** 4")) - 16

the rest work strangely or do not work at all '^' - '^': (2, lambda x, y: x ** y)

print (eval ("2 ^ 4")) - 6?

print (eval ("2x4")) - does not work at all

  if s in OPERATORS or s in "()": yield s 

I think the problem is in this place, but I do not understand why it works with 4 characters and does not want it with the others.

the parser itself is from here, just tried a bit to extend the functionality

https://habrahabr.ru/post/273253/

  • Give examples in which it works incorrectly and how it should be. - gil9red
  • print (eval ("2 4")) - 16 ok, print (eval ("2 ^ 4")) - 6 not ok, print (eval ("2x4")) does not work at all, 1st works when operators are added to the dictionary ('' ': (2, lambda x, y: x ** y)) - djt111
  • um italics spoiled above print (eval ("2 ** 4")) - 16 - djt111
  • At the bottom of the question there is a "edit", use this and update the question. So it will be easier to deal with the problem - gil9red
  • 2
    @ djt111, call the function somehow completely different, so as not to be confused with the built-in eval function. For the built-in eval the ^ operator is XOR, i.e. 2 ^ 4 = 0b0010 ^ 0b0100 = 0b0110 = 6 . Naturally, the built-in eval knows nothing about your x operator. - insolor

0