<p>操作顺序使这变得困难,但并非不可能:</p>
<pre class="lang-py prettyprint-override"><code># helper function to do an operation
def doop(num1, op, num2):
if op == "^":
return num1 ** num2
if op == "+":
return num1 + num2
if op == "-":
return num1 - num2
if op == "*":
return num1 * num2
if op == "/":
return num1 / num2
# if we don't recognize the operation then error
raise Exception("Invalid operation.")
# have a list of sets with operator precedence
precedence = [
{"^"},
{"*", "/"},
{"+", "-"}
]
# hard coded values for testing
nums = [1, 2, 3, 4]
ops = ["+", "-", "*"]
# this represents 1 + 2 - 3 * 4
# start at highest to lowest precedence
for prec in precedence:
# we have to use a while loop to have manual control of `i`
i = 0
while i < len(ops):
# store the current operation
op = ops[i]
# if the operation isn't in the current precedence level we skip it
if op in prec:
# we can get rid of the operation to evaluate it
ops.pop(i)
# we can merge the two numbers around the operation into one
# by performing the calculation
nums[i:i + 2] = [doop(nums[i], op, nums[i + 1])]
# we need to decrease i so we don't skip over the next operation
i -= 1
i += 1
if len(nums) != 1:
raise Exception("Invalid operation count.")
print(nums[0]) # -9
</code></pre>