Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project

Tell us what’s happening:

I think my code is working. It seems to produce all the correct errors and prints the expressions as required yet it is failing all the automated tests.

Your code so far

def check_input_errors(problems):

    # Check if there are too many problems
    if len(problems) > 5:
        print(f'Error: Too many problems.')
        return True
    
    for expression in problems:
        # Check for invalid operators
        if '*' in expression or '/' in expression:
            print(f"Error: Operator must be '+' or '-'.")
            return True
        
        # Split the expression to check the numbers
        parts = expression.split()
        if not (parts[0].isdigit() and parts[2].isdigit()):
            print(f"Error: Numbers must only contain digits.")
            return True
        
        # Check if each number is 4 digits or less
        if len(parts[0]) > 4 or len(parts[2]) > 4:
            print(f"Error: Numbers cannot be more than four digits.")
            return True
  
    return False

def arithmetic_arranger(problems, show_answers=False):
    # Run the input error checks first
    if check_input_errors(problems):
    
        return
    
     
    first_line = ""
    second_line = ""
    dashes = ""
    answers = ""    

    for problem in problems:
        parts = problem.split()
        first_number = parts[0]
        operator = parts[1]
        second_number = parts[2]
    # Calculate the width of the problem
        width = max(len(first_number), len(second_number)) + 2
        first_line += first_number.rjust(width) + "    "
        second_line += operator + second_number.rjust(width - 1) + "    "
        dashes += "-" * width + "    "

        if show_answers:
            if operator == "+":
                answer = str(int(first_number) + int(second_number))
            elif operator == "-":
                answer = str(int(first_number) - int(second_number))
            answers += answer.rjust(width) + "    "
    
    # Print the arranged problems
    print(first_line.rstrip())
    print(second_line.rstrip())
    print(dashes.rstrip())
    if show_answers:
        print(answers.rstrip())

problems = ["24 - 852", "3801 - 2", "45 + 43", "123 + 49", "123 + 49"]

arithmetic_arranger(problems, show_answers=False)







    

Your browser information:

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

Challenge Information:

Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project

returns the problems

return, don’t print. Test and print like this:

print(arithmetic_arranger(["3801 - 2", "123 + 49"]))

or

print(repr(arithmetic_arranger(["3801 - 2", "123 + 49"])))

Your function should return, not print

Okay, I think I’ve amended the code to return results and not print but it still passes none of the tests despite doing exactly what is requested when tested and printed:

def check_input_errors(problems):
    errors=[]
    # Check if there are too many problems
    if len(problems) > 5:
        errors.append('Error: Too many problems.')
    
    for expression in problems:
        # Check for invalid operators
        if '*' in expression or '/' in expression:
            errors.append("Error: Operator must be '+' or '-'.")
            
        
        # Split the expression to check the numbers
        parts = expression.split()
        if not (parts[0].isdigit() and parts[2].isdigit()):
            errors.append("Error: Numbers must only contain digits.")
        
        # Check if each number is 4 digits or less
        if len(parts[0]) > 4 or len(parts[2]) > 4:
            errors.append("Error: Numbers cannot be more than four digits.")
            
  
    return errors

def arithmetic_arranger(problems, show_answers=False):
    # Run the input error checks first
    errors = check_input_errors(problems)
    if errors:
    
        return errors
    
     
    first_line = ""
    second_line = ""
    dashes = ""
    answers = ""    

    for problem in problems:
        parts = problem.split()
        first_number = parts[0]
        operator = parts[1]
        second_number = parts[2]
    # Calculate the width of the problem
        width = max(len(first_number), len(second_number)) + 2
        first_line += first_number.rjust(width) + "    "
        second_line += operator + second_number.rjust(width - 1) + "    "
        dashes += "-" * width + "    "

        if show_answers:
            if operator == "+":
                answer = str(int(first_number) + int(second_number))
            elif operator == "-":
                answer = str(int(first_number) - int(second_number))
            answers += answer.rjust(width) + "    "
    
    # return results
        result = {
        "first_line": first_line.rstrip(),
        "second_line": second_line.rstrip(),
        "dashes": dashes.rstrip(),
        "answers": answers.rstrip() if show_answers else None
    }

    return result

problems = ["24 - 852", "380 - 2", "45 + 43", "123 + 49", "123 + 49"]

arithmetic_arranger(problems, show_answers=False)

Please check the browser console. It has detailed results from the tests. If you don’t understand them, please copy and paste these results here for further help.

I’m lost; the browser console produces this:
// running tests

arithmetic_arranger(["3801 - 2", "123 + 49"])

should return

  3801      123\n-    2    +  49\n------    -----

.

arithmetic_arranger(["1 + 2", "1 - 9380"])

should return

  1         1\n+ 2    - 9380\n---    ------

.

arithmetic_arranger(["3 + 855", "3801 - 2", "45 + 43", "123 + 49"])

should return

    3      3801      45      123\n+ 855    -    2    + 43    +  49\n-----    ------    ----    -----

.

arithmetic_arranger(["11 + 4", "3801 - 2999", "1 + 2", "123 + 49", "1 - 9380"])

should return

  11      3801      1      123         1\n+  4    - 2999    + 2    +  49    - 9380\n----    ------    ---    -----    ------

.

arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49", "888 + 40", "653 + 87"])

should return

'Error: Too many problems.'

.

arithmetic_arranger(["3 / 855", "3801 - 2", "45 + 43", "123 + 49"])

should return

"Error: Operator must be '+' or '-'."

.

arithmetic_arranger(["24 + 85215", "3801 - 2", "45 + 43", "123 + 49"])

should return

'Error: Numbers cannot be more than four digits.'

.

arithmetic_arranger(["98 + 3g5", "3801 - 2", "45 + 43", "123 + 49"])

should return

'Error: Numbers must only contain digits.'

.

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

should return

    3      988\n+ 855    +  40\n-----    -----\n  858     1028

.

arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49", "988 + 40"], True)

should return

   32         1      45      123      988\n- 698    - 3801    + 43    +  49    +  40\n-----    ------    ----    -----    -----\n -666     -3800      88      172     1028

. // tests completed

The instructions ask for a return output of a series of error conditions (where errors exist) and some nicely tabulated expressions with or without answers depending on whether show_answers is True or False.
When you print the output from this code it seems to be doing what was asked of it. If that is the case, what is wrong?

I would like you to try to get the detailed test result from the browser console please. Make sure you are not filtering the output at all. The browser console is reachable through f12 on some browsers. If you can’t open it pls tell us which type of browser you use. If you can’t find the detailed messages (way more detailed than above) then please screenshot your browser and paste the image here so I can see what you are seeing and maybe advise.

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

This is enough to start troubleshooting. Run your own test like this:

print(repr(arithmetic_arranger(["3801 - 2", "123 + 49"])))

Then compare your output to the expected output and see what’s different.

Print the output of your test and you will see the problem right away.

I’m using MS Edge. However I’ve no idea in console mode what I’m looking for. Here is a screenshot:


The really annoying thing is the instructions clearly layout what is required and go to the trouble to provide printed examples of what the table layouts should look like.
My code produces all the correct error messages when those errors are introduced into the data list and they produce all of the tables (with or without calculations) exactly as they’re specified in the instructions with all the right spacings and formats.
I take on board the point that in the small print it doesn’t actually want the tables printed despite the lengthy descriptions and wants a return string. I think I have amended the code to return what was being printed before but the only way I know to test that is to print it first (so I can see it’s right), make sure it conforms and then return it. Nothing the Python syllabus has so far taught us gives us the knowledge to do anything else. On the face of it the code works as it’s doing exactly what was instructed in terms of functionality however for reasons I don’t know it is not passing.
It’s pretty frustrating as it only took a few hours to write but has taken days trying to ascertain what is actually required.

print(repr(arithmetic_arranger(["3801 - 2", "123 + 49"])))

You aren’t far enough to check the console yet. Just look at the preview output.

{'first_line': '  3801      123', 'second_line': '-    2    +  49', 'dashes': '------    -----', 'answers': None}

This is your output. This is what it should be:

  3801      123\n-    2    +  49\n------    -----

This project is all about formatting, not successfully adding numbers together.

Fix this output first, yours looks nothing like the format the instructions give.

  235
+  52
-----

Your output:

{'first_line': '  3801      123', 'second_line': '-    2    +  49', 'dashes': '------    -----', 'answers': None}

the browser console is the one you will see when you click the console button. I’ve highlighted the button in your image.

This is the output of the test printed as you suggested:


It looks exactly what is asked for.
I couldn’t care less about adding numbers together, that is simple.
The method of getting there by splitting it into lines using first_line etc may be different but it matches the examples given and their format.

This is the screen print of the console. What am I supposed to do with this?

Please copy all the errors here.

Are you still failing all of the tests or just the last one? You only need to check the browser console output for the last test.

When I test your code that’s not the output I get.

Please post your updated code.

okay, so now I’ve completely rewritten the entire code without a separate error routine and using a regular expression.
In the preview it produces a nice print out of the expressions as expected however in the freecodecamp console it just says that there are multiple errors but doesn’t say what they are.
I have absolutely no idea what the browser console is saying.
All of a sudden, without changing a single line of the code, the errors disappear and the code passes. I think there are some bugs in the checking. It’s pretty frustrating, teaches nothing and wastes a lot of time,

1 Like

Nothing’s perfect, but I’m glad you got it!

You’re welcome! :wave: