Arithmetic Formatter项目:实现算式横向排列的方法咨询
Arithmetic Formatter横向排列实现思路
现有代码
def arithmetic_arranger(problems, show_answers=False): #error handling:problems greater than 5 if len(problems) > 5: return 'Error: Too many problems.' #splitting problems between operator and numbers split_problems = '' for problem in problems: numberA, operator, numberB= problem.split() #error handling of problems- only digits allowed if not (numberA.isdigit() and numberB.isdigit()): return 'Error: Numbers must only contain digits.' #error handling of problems-no more than 4 digits if len(numberA) > 4 or len(numberB) > 4: return 'Error: Numbers cannot be more than four digits.' # Error handling of problems- incorrect operator if operator not in ('+', '-'): return "Error: Operator must be '+' or '-'" #define needed width width = max(len(numberA), len(numberB)) + 2 #arranging the sums split_problems += numberA.rjust(width) + '\n' split_problems += operator + numberB.rjust(width - 1) + '\n' split_problems += '-' * width + '\n' return split_problems print(f'\n{arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])}')
当前问题
现有代码会把每个算式纵向依次排列,输出形式如下:
xxx +xx ___ xxx -xx ___ xxx +xx ___ xxx +xx ___
需要改为多个算式横向并排展示(每个算式间用4个空格分隔)的形式。
实现思路
- 放弃直接拼接成单字符串的方式,改为按行分组存储:创建3个(若需显示答案则为4个)空列表,分别对应所有算式的第一行(第一个数字)、第二行(运算符+第二个数字)、第三行(分隔线)、第四行(计算结果)。
- 遍历每个算式时,格式化好当前算式的对应行内容,将其添加到对应的列表中。比如处理完一个算式,就把右对齐的第一个数字加入第一行列表,运算符加右对齐的第二个数字加入第二行列表,对应长度的分隔线加入第三行列表。
- 所有算式处理完成后,将每一行的列表元素用4个空格连接,形成完整的行字符串。
- 最后把所有行字符串用换行符
\n拼接,得到横向排列的结果。
内容的提问来源于stack exchange,提问作者Nolwazi Mbatha
相关产品推荐
相关产品推荐

