Scientific Computing with Python Projects - Arithmetic Formatter

Tell us what’s happening:

my algorithm gives right results but it stills giving me an error

Your code so far

def arithmetic_arranger(problems, show_answers=False):
    formatted_lines = []
    
    if len(problems) > 5:
        return 'Error: Too many problems.'
    for problem in problems:
        # Split the problem into operands and operator
        operand1, operator, operand2 = problem.split()

        # Validate the format of the problem
        if operator not in ['+', '-']:
            return "Error: Operator must be '+' or '-'."

        if not (operand1.isdigit() and operand2.isdigit()):
            return "Error: Numbers must only contain digits."

        if len(operand1) > 4 or len(operand2) > 4:
            return "Error: Numbers cannot be more than four digits."
        # Determine the maximum length of the operands
        if len(operand1) < len(operand2):
            d = len(operand2) - len(operand1)
        else:
            d = 0
        formatted_lines.append(f"{' '*(2 + d)}{operand1}    ")

        # If show_answers is True, append the result
    formatted_lines.append(f'\n')
    for problem in problems:
        operand1, operator, operand2 = problem.split()
        if len(operand2) < len(operand1):
            d = len(operand1) - len(operand2)
        else:
            d = 0        
        formatted_lines.append(f"{operator}{' '*(1 + d)}{operand2}    ")    
    
    formatted_lines.append(f'\n')   
    
    for problem in problems:
        operand1, operator, operand2 = problem.split()
        max_length = max(len(operand1), len(operand2))
        formatted_lines.append(f"{'-' * (max_length + 2)}    ")       
    formatted_lines.append(f'\n')
    for problem in problems:
        operand1, operator, operand2 = problem.split()
        max_length = max(len(operand1), len(operand2))
        if operator == '+':
            result = int(operand1) + int(operand2)
        else:
            result = int(operand1) - int(operand2)
        if show_answers:        
            formatted_lines.append(f"{' '*((max_length +2)-len(str(result)))}{result}    ")   
   
    # Join the formatted lines with proper spacing
    if show_answers:
        return ''.join(formatted_lines).rstrip()
    else:
        return ''.join(formatted_lines[:3]).rstrip()
print(arithmetic_arranger(["3 + 855", "988 + 40","12 - 876"], True))


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36

Challenge Information:

Scientific Computing with Python Projects - Arithmetic Formatter

if you press F12 you can see more details from the tests. You have extra spaces at the end of each line that you should not have there