Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project

Tell us what’s happening:

The functionality of my code is there. However, the formatting of my output is wrong, it goes from upwards to downwards and not left to right. How should I proceed?

Your code so far

def arithmetic_arranger(problems, show_answers=False):

    if len(problems) > 5:
        print('Error: Too many problems.')
        return

    for problem in problems:
        parts = problem.split()
        if parts[0].isnumeric() and parts[2].isnumeric():
            if len(parts[0]) < 5 and len(parts[2]) < 5:
                if parts[1] == '+':
                    sum = int(parts[0]) + int (parts[2])
                elif parts [1] == '-':
                    sum = int(parts[0]) - int(parts[2])
                else:
                    print("Error: Operator must be '+' or '-'.")
                    return
            else: 
                print('Error: Numbers cannot be more than four digits.')
                return
        else:
            print('Error: Numbers must only contain digits.')
            return

        first_line = []
        second_line = []
        dashes = []
        answers = []

        parts = problem.split()
        width = max(len(parts[0]), len(parts[2])) + 2
        first_line.append(f"{parts[0]:>{width}}")
        second_line.append(f"{parts[1]} {parts[2]:>{width-2}}")
        dashes.append('-' * width)
        if show_answers:
            answer = str(eval(problem))
            answers.append(f"{answer:>{width}}")
            
        # Join the lines with spaces
        print("    ".join(first_line))
        print("    ".join(second_line))
        print("    ".join(dashes))
        if show_answers:
            print("    ".join(answers))

arithmetic_arranger(["3 + 855", "988 + 40"], True)
            
    
    


Your browser information:

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

Challenge Information:

Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project

In case of printing, there isn’t really any simpler way than formatting it line by line. So ie. everything from line 1 is printed first, only then next line is proceeded.

Keep in mind also that function is not expected to print anything on it own.

UPDATE
I managed to fix it by moving my lists and print statements outside the for loop.

However I now face another problem. After running the test, it still returns incorrect for all, despite the output to be correct when I put the function call in my code.

Thank you for your reply. Are you referring to the last line of my code with regards to the function not expected to print anything on its own?

Function should return string with arranged problems, or string with error.

1 Like

Thank you! I managed to solve it.

1 Like