Tell us what’s happening:
I get this error and I don’t understand what’s wrong:
6. arithmetic_arranger([“3 / 855”, “3801 - 2”, “45 + 43”, “123 + 49”]) should return “Error: Operator must be ‘+’ or ‘-’.”.
Your code so far
def arithmetic_arranger(problems, show_answers=False):
if len(problems) > 5:
return 'Error: Too many problems.'
# Listas para cada línea del resultado
line1 = []
line2 = []
line3 = []
line4 = []
for problem in problems:
num1, operator, num2 = problem.split()
if operator not in ['+', '-']:
return 'Error: Operator must be "+" or "-".'
if not num1.isdigit() or not num2.isdigit():
return 'Error: Numbers must only contain digits.'
if len(num1) > 4 or len(num2) > 4:
return 'Error: Numbers cannot be more than four digits.'
# Calcular el ancho necesario para la operación
width = max(len(num1), len(num2)) + 2 # +2 para el operador y espacio
# Formatear cada línea
line1.append(f'{num1:>{width}}')
line2.append(f'{operator} {num2:>{width-2}}')
line3.append('-' * width)
if show_answers:
if operator == '+':
result = str(int(num1) + int(num2))
else:
result = str(int(num1) - int(num2))
line4.append(f'{result:>{width}}')
# Juntar los resultados con 4 espacios entre cada problema
arranged_problems = ' '.join(line1) + '\n' + ' '.join(line2) + '\n' + ' '.join(line3)
if show_answers:
arranged_problems += '\n' + ' '.join(line4)
return arranged_problems
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36
Challenge Information:
Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project