There is such code:

exp = input ('Expression: ').split(' ') for sim in exp: print (sim) if sim == '*': num1 = int ( exp[ exp.index(sim) - 1 ] ) num2 = int ( exp[ exp.index(sim) + 1 ] ) del exp[ exp.index(sim) - 1 ] del exp[ exp.index(sim) + 1 ] exp[ exp.index(sim) ] = num1 * num2 print (exp) 

An expression of the form "2 + 2 * 3 * 4" is entered into the input. Prototic, this line is divided into parts through spaces ( slpit(' ') ). Next in the resulting list is the search for the multiplication symbol (*). When it is found, its neighboring values ​​are deleted, and it changes to the product of those values. After that, I need to sort out the values ​​from the very beginning, as this example: "2 + 2 * 3 * 4" - my program will turn into "2 + 6 * 4". (Skip the next multiplication symbol.)

  • one
    You can just write eval(exp) and that's it. Why invent something - Twiss
  • @Twiss, I would not advise eval ;) - MaxU
  • And if the user enters the expression without spaces and / or with parentheses? In general, if you want to write a normal parser for an arithmetic expression, it is better to look for information on the network about how to do it correctly or use a ready-made solution ( example ). - MaxU
  • @MaxU, I do this not for practical use, but for what is just to be done) I make up problems for myself, I solve them myself. - Don2Quixote

1 answer 1

An example with recursion:

 def d(input_): print input_ if "*" in input_: smb = input_.index("*") lf = input_.pop(smb - 1) rf = input_.pop(smb) input_[smb - 1] = int(lf) * int(rf) print input_[smb - 1] d(input_) elif "+" in input_ and "*" not in input_: smb = input_.index("+") lf = input_.pop(smb - 1) rf = input_.pop(smb) input_[smb - 1] = int(lf) + int(rf) print input_[smb - 1] d(input_) elif len(input_) == 1: print input_[0] else: pass d("2 + 2 * 3 * 4".split(" ")) # ['2', '+', '2', '*', '3', '*', '4'] # 6 # ['2', '+', 6, '*', '4'] # 24 # ['2', '+', 24] # 26 # [26] # 26