You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现算术题竖式并排排列的技术求助

算术题竖式并排排列解决方案

现有需求是将算术题以整齐的竖式列形式并排输出,原代码只能逐个垂直输出题目,无法实现并排对齐。

原代码:

def arithmetic_arranger(problems, calculate = False):
    for problem in problems:
        problem = problem.split()
        first_number = problem[0]
        second_number = problem[2]
        sign = problem[1]
        
        try:
            first_number = int(first_number) 
            second_number = int(second_number)   
        except:
            print('Error: Numbers must only contain digits.')
            break

        if calculate is True:
            if sign == '+':
                result = first_number + second_number
            else:
                result = first_number - second_number

        print(f'{first_number}\n{sign} {second_number}\n-----')
        
        if calculate is True:
            print(result)
arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"], True)

当前输出:

32
+ 8
-----
40
1
- 3801
-----
-3800
9999
+ 9999
-----
19998
523
- 49
-----
474

期望输出:

32         1      9999      523
+  8    - 3801    + 9999    -  49
----    ------    ------    -----
  40     -3800     19998      474

修改后的代码

def arithmetic_arranger(problems, calculate=False):
    top_line = []
    middle_line = []
    bottom_line = []
    result_line = []
    
    for problem in problems:
        parts = problem.split()
        first_num = parts[0]
        sign = parts[1]
        second_num = parts[2]
        
        # 验证数字合法性
        if not (first_num.isdigit() and second_num.isdigit()):
            print('Error: Numbers must only contain digits.')
            return
        
        first_int = int(first_num)
        second_int = int(second_num)
        
        # 计算每列的宽度:取两个数字的长度最大值 + 2(符号和空格)
        col_width = max(len(first_num), len(second_num)) + 2
        
        # 格式化各行内容
        top_line.append(f"{first_int:>{col_width}}")
        middle_line.append(f"{sign} {second_int:>{col_width - 2}}")
        bottom_line.append('-' * col_width)
        
        # 计算结果并格式化
        if calculate:
            if sign == '+':
                res = first_int + second_int
            else:
                res = first_int - second_int
            result_line.append(f"{res:>{col_width}}")
    
    # 拼接各行,用4个空格分隔每列
    output = '    '.join(top_line) + '\n' + '    '.join(middle_line) + '\n' + '    '.join(bottom_line)
    if calculate:
        output += '\n' + '    '.join(result_line)
    
    print(output)

arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"], True)

关键说明

  1. 按行存储内容:创建四个列表分别存储每一行的所有列内容,统一处理后再拼接成行,避免逐个输出的混乱。
  2. 列宽度计算:每列宽度取两个数字的最大长度加2(符号占1位、空格占1位),确保所有内容在列内有足够空间对齐。
  3. 格式化对齐:使用>{width}格式化语法实现右对齐,保证数字在列内靠右排列,符合竖式计算的视觉习惯。
  4. 拼接输出:用4个空格分隔每列内容,将各行拼接后一次性输出,实现题目并排的效果。

内容的提问来源于stack exchange,提问作者Dankin Dior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:11:29