同一段Python代码在Leetcode与本地运行结果不一致排查
逆波兰表达式求值:本地与LeetCode提交结果不一致问题
本地PyCharm测试LeetCode逆波兰表达式求值问题时,输入tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]能得到正确结果22,但将代码粘贴到LeetCode提交后返回12,问题出在除法的处理逻辑和Python版本差异。
本地测试代码
def main(): # tokens = ["2", "1", "+", "3", "*"] # tokens = ["4", "13", "5", "/", "+"] tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] print(eval_rpn(tokens)) def eval_rpn(tokens): stack = [] ops = ["+", "-", "*", "/"] for c in tokens: if c not in ops: stack.append(c) else: num2 = int(stack.pop()) num1 = int(stack.pop()) if c == "+": total = num1 + num2 elif c == "-": total = num1 - num2 elif c == "*": total = num1 * num2 else: # The only operator left is division total = num1 / num2 stack.append(total) return stack[-1] if __name__ == "__main__": main()
LeetCode提交代码
class Solution(object): def evalRPN(self, tokens): stack = [] ops = ["+", "-", "*", "/"] for c in tokens: if c not in ops: stack.append(c) else: num2 = int(stack.pop()) num1 = int(stack.pop()) if c == "+": total = num1 + num2 elif c == "-": total = num1 - num2 elif c == "*": total = num1 * num2 else: total = num1 / num2 stack.append(total) return stack[-1]
问题原因
LeetCode部分Python环境(如Python2)中,整数间使用/做除法是地板除(向下取整),而本地使用的Python3中/是浮点数除法,两者对负数除法的处理差异导致结果不同:
- 计算到
6 / -132时:- Python3中
6 / -132得到-0.04545...,后续乘以10得到-0.4545...,转为整数时截断为0,最终计算出正确结果22。 - Python2中
6 / -132直接得到整数-1,后续乘以10得到-10,最终计算结果为-10+17+5=12。
- Python3中
另外,题目要求除法结果向零截断(即无论正负,取最接近0的整数),原代码的除法逻辑没有符合这个要求,依赖Python版本的行为导致结果不一致。
修复方案
修改除法逻辑,确保无论Python版本,除法都向零截断,有两种常用方式:
方式1:使用math.trunc
先导入math模块,将除法部分改为:
import math # ... else: total = math.trunc(float(num1) / num2)
方式2:手动处理整数除法
通过判断正负,调整地板除的结果:
else: total = num1 // num2 # 当被除数和除数异号,且有余数时,结果加1实现向零截断 if (num1 * num2 < 0) and (num1 % num2 != 0): total += 1
修改后提交LeetCode,即可得到正确结果22。
内容的提问来源于stack exchange,提问作者usefulmellow
相关产品推荐
相关产品推荐

