Python算术计算器运算式下方横线打印长度错误问题
问题排查与修复方案
故障原因
代码中计算最大操作数长度的逻辑存在错误:
- 原代码
n = len(x) if (x > y) else len(y)里的x>y是字符串按字典序比较,不是比较两个操作数字符串的长度。 - 第四个运算式中x为
'123'、y为'49',字符串比较时'123' < '49',所以会取len(y)=2,最终导致横线只打印2个,不符合预期。
修复方案
将长度判断逻辑修改为比较两个操作数的长度即可:
把n = len(x) if (x > y) else len(y)
替换为n = max(len(x), len(y)),该写法可读性更高,也能准确取到两个操作数的最大长度。
额外优化:原打印逻辑每行末尾会残留多余空格,给每行字符串都加上rstrip()处理可以让输出更规范。
修正后完整代码
equations = ["32 + 698", "3801 - 2", "45 + 43", "123 + 49"] def arithmetic_equation(arr): finalLine = '' anotherLine = '' thirdLine = '' fourthLine = '' space = 4 for item in equations: parts = item.split() x = parts[0] y = parts[2] c = parts[1] if c == '+': z = int(x) + int(y) else: z = int(x) - int(y) # 修复:取两个操作数的最大长度 n = max(len(x), len(y)) stepOne = x.rjust(n + 2) stepTwo = c + ' ' + y.rjust(n) stepThree = ' ' + '-' * n stepFour = str(z).rjust(n + 2) finalLine += stepOne + ' ' * space anotherLine += stepTwo + ' ' * space thirdLine += stepThree + ' ' * space fourthLine += stepFour + ' ' * space print(finalLine.rstrip() + '\n' + anotherLine.rstrip() + '\n' + thirdLine.rstrip() + '\n' + fourthLine.rstrip()) arithmetic_equation(equations)
内容的提问来源于stack exchange,提问作者mage76
相关产品推荐
相关产品推荐

