Den*_*gen 1 python math types for-loop calculator
If a have the string calculation = '1+1x8'. How can I convert this into calculation = 1+1*8? I tried doing something like
for char in calculation:
if char == 'x':
calculation = calculation.replace('x', *)
# and
if char == '1':
calculation = calculation.replace('1', 1)
Run Code Online (Sandbox Code Playgroud)
This clearly doesn't work, since you can't replace just one character with an integer. The entire string needs to be an integer, and if I do that it doesn't work either since I can't convert 'x' and '+' to integers
让我们用更复杂的字符串作为一个例子:1+12x8。接下来是一个粗略的概述;您需要为每个步骤提供实施。
首先,将其标记化,1+12x8变成['1', '+', '12', 'x', '8']。对于这一步,您需要编写一个标记器或一个词法分析器。这是定义运算符和文字的步骤。
接下来,将令牌流转换为解析树。也许您将树表示为S表达式 ['+', '1', ['x', '12', '8']]或[operator.add, 1, [operator.mul, 12, 8]]。此步骤需要编写一个解析器,该解析器需要定义诸如运算符优先级之类的东西。
最后,您编写了一个评估程序,可以将您的解析树减少为单个值。分两步执行可能会产生
[operator.add, 1, [operator.mul, 12, 8]] 至 [operator.add, 1, 96][operator.add, 1, 96] 至 97