Build an arithmetic formatter project

I have been coding this project under scientific computing with python and my return values are correct in terms of display but it did not pass the test cases.

def arithmetic_arranger(problems, show_answers=False):
    '''
    Takes a list of strings containing arithemtic equations of addition and subtraction and converts and returns them in an elementary illustrated working of the calculation.
    '''
    
    #Check if problems are more than 5.
    if len(problems) > 5:
        raise ValueError('Error: Too many problems.')
    
    #Will accumulate the values for each row i.e., the first number, the second number with operator, the dashed line and the answer when required.
    row1 = []
    row2 = []
    row3 = []
    row4 = []

    #Verifies further if input is correct and then converts input if correct.
    for element in problems:
        element = element.split(' ')
        #print(element)
        #Checks if only addition or subtraction operator present.
        if element[1] == '+' or element[1] == '-':
            #Check if numbers are numerical.
            if element[0].isnumeric() and element [2].isnumeric():
                #Check if numbers are not longer than 4 digits.
                if len(element[0]) <=4 and len(element[2])<=4:
                    #Assigns variables from element list.
                    num1, num2, operator = element[0], element[2], element[1]   

                    ans = 0 #Default value for answer.

                    #print(num1, num2, operator )
                    #Check if default parameter was set to True
                    if show_answers == True:
                        #Adds values when operator is '+'
                        if operator == '+':
                            ans = int(num1) + int(num2)
                        #Subtracts balues when operator is '-'
                        elif operator == '-':
                            ans = int(num1) - int(num2)
            
                    #Calculates total length of arithmetic working
                    total_length = max(len(num1), len(num2)) + 2 # Adds 2 which is to account for the operator and the space between the operator and numbers.

                    #Calculate right alignment
                    space = ' '
                    #Check difference between total_length and length of number to see how many spaces to push number to the right.
                    num1_indenter = total_length-len(num1) 
                    num2_indenter = total_length-len(num2)-1
                    
                    # Spacing between each arithmetic calculation
                    separator = '  '
                    
                    #Check if ans is stil default or has an actual value.
                    if ans == 0:
                        ans_indenter = 0 #Right alignment set to 0.
                        row4.append(''+separator) #Appends nothing.
                    else:
                        ans_indenter = total_length-len(str(ans)) #Calculate right alignment
                        row4.append(space*ans_indenter+str(ans)+separator) #Appends right alignment, answer and additional 4 spaces to separate itself from other arithmetic calculations.
                    #print(row4)
                    
                    #For making dashed line
                    line = '-'
                    
                    #The following appends right alignment, the respective number/operator and four spaces to separate itself from other arithmetic calculations.
                    row1.append(space*num1_indenter+num1+separator)
                    #print(row1)
                    row2.append(operator+space*num2_indenter+num2+separator)
                    #print(row2)
                    row3.append(line*total_length+separator)
                    #print(row3)

                else:
                    return ValueError('Error: Numbers cannot be more than four digits.')
            else:
                return ValueError("Error: Numbers must only contain digits.")
        else:
            return ValueError("Error: Operator must be '+' or '-'.")

    #Holds final display of arithmetic working.
    final_display = f"{separator.join(row1)}\n{separator.join(row2)}\n{separator.join(row3)}\n{separator.join(row4)}"

    return final_display

print(f'{arithmetic_arranger(["32 + 8", "1 - 3081", "9999 + 9999", "523 - 49"], True)}')

I’m not entirely sure why it’s not passing the test cases but it could be due to the spacing sensitivity?

Should the forth row always show?

I also copied one of the test case expected results and printed it but it gives this output:
image

When I remove the True and set it to default parameter, it won’t show the fourth row

Are you sure about that though. The message needs to match down to every whitespace

I am not sure, I just went by how the output looks and throughout the code, I added the necessary spacing, etc.

When you ask for help it would be great if you could also include the link to the step/challenge/project.

Let’s take a look at the browser console, below I will leave more details on how to read the errors.

AssertionError: '  3801      123  \n-    2    +  49  \n------    -----  \n      ' 
             != '  3801      123\n-    2    +  49\n------    -----'
-   3801      123  
?                --
+   3801      123
- -    2    +  49  
?                --
+ -    2    +  49
- ------    -----  
?                ---
+ ------    ------ 

You have extra spaces on each line


The assertion error and diff gives you a lot of information to track down a problem. For example:

AssertionError: 'Year' != 'Years'
- Year
+ Years
?     +

Your output comes first, and the output that the test expects is second.

AssertionError: ‘Year’ != ‘Years’

Your output: Year does not equal what’s expected: Years

This is called a diff, and it shows you the differences between two files or blocks of code:

- Year
+ Years
?     +

- Dash indicates the incorrect output
+ Plus shows what it should be
? The Question mark line indicates the place of the character that’s different between the two lines. Here a + is placed under the missing s .

Here’s another example:

E       AssertionError: Expected different output when calling "arithmetic_arranger()" with ["3801 - 2", "123 + 49"]
E       assert '  3801      123    \n   - 2     + 49    \n------    -----    \n' == '  3801      123\n-    2    +  49\n------    -----'
E         -   3801      123
E         +   3801      123    
E         ?                ++++
E         - -    2    +  49
E         +    - 2     + 49    
E         - ------    -----
E         + ------    -----    
E         ?                +++++

The first line is long, and it helps to view it as 2 lines in fixed width characters, so you can compare it character by character:

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

Again, your output is first and the expected output is second. Here it’s easy to see extra spaces or \n characters.

E         -   3801      123
E         +   3801      123    
E         ?                ++++

Here the ? line indicates 4 extra spaces at the end of a line using four + symbols. Spaces are a little difficult to see this way, so it’s useful to use both formats together.

I hope this helps interpret your error!

Hi, thank you so much for the comprehensive information but I do not understand how to open the console browser, it says to press F12, but it opens the websites digital certification instead and when I try combinations of ctrl, shift, alt with f12, it does not do anything. I also do not understand how to get the colours of red and green in the console. When I press console, I get this:

Please don’t take a picture of your computer and post it

I’m so sorry, I didn’t know and when i pressed windows shift s to take a snippet, it wasnt working

oh yeah, I will share the link for the project next time

you can google how to open the console for your browser, but in the dev tools there is also the Console:

Hi, I have checked with the console but I am still confused with what’s going on. I want to clarify some things first. When it runs the tests, I should remove the print statement at the end of my code right? I have the print statement there so I can see what my output is.

Next is, I used rstrip() to remove trailing whitespace so it does not detect extra space at the end, have I used rstrip() correctly in my code below?

And, when I look at the assertion errors, I see the extra spaces or so I think I have seen what the errors are trying to tell me then I removed them in my code but the output on the terminal on both visual studio code and freecodecamp’s one looks weird. It is still the original code below that shows the correct output on both terminals but it still didn’t pass the test cases. I also don’t understand what the error messages exactly mean in the console. For example, in the snippet below, what is it testing for? is it 3801 - 2 and 123 + 49? because it is one of the test cases but its not supposed to have an answer displayed but in the browser console, it tests with the answer. So I’m still confused with what’s wrong with the code.

def arithmetic_arranger(problems, show_answers=False):
    '''
    Takes a list of strings containing arithemtic equations of addition and subtraction and converts and returns them in an elementary illustrated working of the calculation.
    '''
    
    #Check if problems are more than 5.
    if len(problems) > 5:
        raise ValueError('Error: Too many problems.')
    
    #Will accumulate the values for each row i.e., the first number, the second number with operator, the dashed line and the answer when required.
    row1 = []
    row2 = []
    row3 = []
    row4 = []

    #Verifies further if input is correct and then converts input if correct.
    for element in problems:
        element = element.split(' ')
        #print(element)
        #Checks if only addition or subtraction operator present.
        if element[1] == '+' or element[1] == '-':
            #Check if numbers are numerical.
            if element[0].isnumeric() and element [2].isnumeric():
                #Check if numbers are not longer than 4 digits.
                if len(element[0]) <=4 and len(element[2])<=4:
                    #Assigns variables from element list.
                    num1, num2, operator = element[0], element[2], element[1]   

                    ans = 0 #Default value for answer.

                    #print(num1, num2, operator )
                    #Check if default parameter was set to True
                    if show_answers == True:
                        #Adds values when operator is '+'
                        if operator == '+':
                            ans = int(num1) + int(num2)
                        #Subtracts balues when operator is '-'
                        elif operator == '-':
                            ans = int(num1) - int(num2)
            
                    #Calculates total length of arithmetic working
                    total_length = max(len(num1), len(num2)) + 2 # Adds 2 which is to account for the operator and the space between the operator and numbers.

                    #Calculate right alignment
                    space = ' '
                    #Check difference between total_length and length of number to see how many spaces to push number to the right.
                    num1_indenter = total_length-len(num1) 
                    num2_indenter = total_length-len(num2)-1
                    
                    # Spacing between each arithmetic calculation
                    separator = '  '
                    
                    #Check if ans is stil default or has an actual value.
                    if ans == 0:
                        ans_indenter = 0 #Right alignment set to 0.
                        row4.append(''+separator) #Appends nothing.
                    else:
                        ans_indenter = total_length-len(str(ans)) #Calculate right alignment
                        row4.append(space*ans_indenter+str(ans)+separator) #Appends right alignment, answer and additional 4 spaces to separate itself from other arithmetic calculations.
                    #print(row4)
                    
                    #For making dashed line
                    line = '-'
                    
                    #The following appends right alignment, the respective number/operator and four spaces to separate itself from other arithmetic calculations.
                    row1.append(space*num1_indenter+num1+separator)
                    #print(row1)
                    row2.append(operator+space*num2_indenter+num2+separator)
                    #print(row2)
                    row3.append(line*total_length+separator)
                    #print(row3)

                else:
                    return ValueError('Error: Numbers cannot be more than four digits.')
            else:
                return ValueError("Error: Numbers must only contain digits.")
        else:
            return ValueError("Error: Operator must be '+' or '-'.")

    #Holds final display of arithmetic working.
    final_display = f" {separator.join(row1)}\n {separator.join(row2)}\n {separator.join(row3)}\n {separator.join(row4)}"

    return final_display.rstrip()

print(arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"], True))



this is not necessary, you can keep it

if you want to remove the spaces from the end of the string yes, if you want to remove the spaces from each line then no

yes, those are the problems, also no, it’s not testing with an answer, and your function does not output an answer either

this is printing with an answer


for your assertion error, let’s look at a single issue:

AssertionError: '   3801      123  \n -    2    +  49  \n ------    -----' 
             != '  3801      123\n-    2    +  49\n------    -----'
                   |

you have an extra space at the beginning,

you are adding more spaces in this string

Does that mean I must not have any space at the beginning or just one space?


I removed all the extra spaces in the above according to this:

but it doesn’t seem to work. am I removing it correctly?

post your updated code, screenshots of code are not debuggable

right, sorry about that haha.

def arithmetic_arranger(problems, show_answers=False):
    '''
    Takes a list of strings containing arithemtic equations of addition and subtraction and converts and returns them in an elementary illustrated working of the calculation.
    '''
    
    #Check if problems are more than 5.
    if len(problems) > 5:
        raise ValueError('Error: Too many problems.')
    
    #Will accumulate the values for each row i.e., the first number, the second number with operator, the dashed line and the answer when required.
    row1 = []
    row2 = []
    row3 = []
    row4 = []

    #Verifies further if input is correct and then converts input if correct.
    for element in problems:
        element = element.split(' ')
        #print(element)
        #Checks if only addition or subtraction operator present.
        if element[1] == '+' or element[1] == '-':
            #Check if numbers are numerical.
            if element[0].isnumeric() and element [2].isnumeric():
                #Check if numbers are not longer than 4 digits.
                if len(element[0]) <=4 and len(element[2])<=4:
                    #Assigns variables from element list.
                    num1, num2, operator = element[0], element[2], element[1]   

                    ans = 0 #Default value for answer.

                    #print(num1, num2, operator )
                    #Check if default parameter was set to True
                    if show_answers == True:
                        #Adds values when operator is '+'
                        if operator == '+':
                            ans = int(num1) + int(num2)
                        #Subtracts balues when operator is '-'
                        elif operator == '-':
                            ans = int(num1) - int(num2)
            
                    #Calculates total length of arithmetic working
                    total_length = max(len(num1), len(num2)) + 2 # Adds 2 which is to account for the operator and the space between the operator and numbers.

                    #Calculate right alignment
                    space = ' '
                    #Check difference between total_length and length of number to see how many spaces to push number to the right.
                    num1_indenter = total_length-len(num1) 
                    num2_indenter = total_length-len(num2)-1
                    
                    # Spacing between each arithmetic calculation
                    separator = '  '
                    
                    #Check if ans is stil default or has an actual value.
                    if ans == 0:
                        ans_indenter = 0 #Right alignment set to 0.
                        row4.append(''+separator) #Appends nothing.
                    else:
                        ans_indenter = total_length-len(str(ans)) #Calculate right alignment
                        row4.append(space*ans_indenter+str(ans)+separator) #Appends right alignment, answer and additional 4 spaces to separate itself from other arithmetic calculations.
                    #print(row4)
                    
                    #For making dashed line
                    line = '-'
                    
                    #The following appends right alignment, the respective number/operator and four spaces to separate itself from other arithmetic calculations.
                    row1.append(space*num1_indenter+num1+separator)
                    #print(row1)
                    row2.append(operator+space*num2_indenter+num2+separator)
                    #print(row2)
                    row3.append(line*total_length+separator)
                    #print(row3)

                else:
                    return ValueError('Error: Numbers cannot be more than four digits.')
            else:
                return ValueError("Error: Numbers must only contain digits.")
        else:
            return ValueError("Error: Operator must be '+' or '-'.")

    #Holds final display of arithmetic working.
    final_display = f"{separator.join(row1)}\n{separator.join(row2)}\n{separator.join(row3)}\n{separator.join(row4)}"

    return final_display.rstrip()

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

#if statement to to check if show_answers true or false, then append nothing or ans.

# Redo spacing to match sequence of tests.
AssertionError: '  3801      123  \n-    2    +  49  \n------    -----'
             != '  3801      123\n-    2    +  49\n------    -----'
                                |

now it’s better, you have two extra spaces after 123, before the end of the line
you can find where it is added and change that, or add something to final_display

1 Like

Okay, I passed some of the test cases, I am starting to understand what’s the issue, thank you so much for helping me out!

1 Like