FreeCodeCamp Python算术格式化项目输出不匹配报错求助
报错原因分析
对比测试返回的实际输出和预期输出可以直接定位问题:你的返回结果每一行的末尾都多了4个多余空格。
# 你的实际输出 ' 3801 123 \n- 2 + 49 \n------ ----- ' # 预期输出 ' 3801 123\n- 2 + 49\n------ -----'
问题出在循环拼接逻辑:你处理每一道题的时候,都在内容末尾加了4个空格作为题目间隔,最后一道题的末尾也被加上了多余的4个空格,不符合格式要求。
修复方案
建议用列表存储每道题的各部分内容,最后用' '.join()方法拼接,自动避免末尾多余空格,修改后的完整代码如下:
def arithmetic_arranger(problems, solve=False): if len(problems) > 5: return "Error: Too many problems." # 改用列表存储各部分内容 top = [] bottom = [] dashes = [] solutions = [] for problem in problems: split_terms = problem.split(' ') if len(split_terms) != 3: return 'Please format probems as "x + y" with spaces between numbers and operators' op = split_terms[1] num1, num2 = split_terms[0], split_terms[2] if op not in ['+', '-']: return "Error: Operator must be '+' or '-'." try: int(num1) int(num2) except: return "Error: Numbers must only contain digits." if len(num1) > 4 or len(num2) > 4: return "Error: Numbers cannot be more than four digits." # 计算各部分长度 max_len = max(len(num1), len(num2)) width = max_len + 2 # 拼接单题各部分内容 top.append(num1.rjust(width)) bottom.append(f"{op} {num2.rjust(max_len)}") dashes.append('-' * width) if solve: res = str(eval(problem)) solutions.append(res.rjust(width)) # 用四个空格拼接各部分,自动无末尾空格 arranged_problems = ' '.join(top) + '\n' + ' '.join(bottom) + '\n' + ' '.join(dashes) if solve: arranged_problems += '\n' + ' '.join(solutions) return arranged_problems
内容的提问来源于stack exchange,提问作者Justin G
相关产品推荐
相关产品推荐

