Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project

Tell us what’s happening:

Can someone please help me get started with the formatting? I’m going through what I learned in the lessons before this project but don’t know what would help with the “space between the operands, the operator on the same line as the second operand, the numbers being right-aligned”.

Your code so far

def arithmetic_arranger(problems, show_answers=False):

    #1) Check if there are too many problems supplied
    if len(problems) >= 5:
        print(f'Error: Too many problems.')

    for problem in problems:    
        parts = problem.split() #The split() method splits the substring "problem" into a list called parts, default separator is any whitespace. Split once, store the result
        first_operand = parts[0]
        operator = parts[1]
        second_operand = parts[2]
        
        #Error checking
        if operator not in ["+", "-"]:
            print("Error: Operator must be '+' or '-'.")

        if not (first_operand.isdigit() and second_operand.isdigit()):
            print("Error: Numbers must only contain digits.") 

        if len(first_operand) > 4 or len(second_operand) > 4:
            print('Error: Numbers cannot be more than four digits.')

        #Formatting
        first_line = ''
        second_line = ''
        dashes = ''
        answer_line = ''

        #There should be a single space between the operator and the longest of the two operands, the operator will be on the same line as the second operand, both operands will be in the same order as provided (the first will be the top one and the second will be the bottom).
        


    return problems

print(f'\n{arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])}')

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36

Challenge Information:

Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project

It should print like the example

  235
+  52
-----

Currently if I print what your function returns:

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

It returns a list.

You want it to look like this:

   32      3801      45      123
+ 698    -    2    + 43    +  49
-----    ------    ----    -----

Print some spaces… then 32 more spaces, 3801, six spaces, 45, more spaces, 123 then a newline, a plus, a space, 698… etc.

The tests even show you exactly what the raw string to build should look like:

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

So if you print using repr():

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

it will look like this:

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

I hope this helps?

This is what I’v coded so far, but it is showing an indentation error for line 41 which is the first_line definition. I don’t understand how the indentation is wrong?

def arithmetic_arranger(problems, show_answers=False):

    #1) Check if there are too many problems supplied
    if len(problems) >= 5:
        print(f'Error: Too many problems.')

    first_line = ''
    second_line = ''
    answer_line = ''
    dashes = ''

    for problem in problems:    
        parts = problem.split() #The split() method splits the substring "problem" into a LIST called parts, default separator is any whitespace. Split once, store the result
        first_operand = parts[0]
        operator = parts[1]
        second_operand = parts[2]
        
        #Error checking
        if operator not in ['+', '-']:
            print("Error: Operator must be '+' or '-'.")

        if not (first_operand.isdigit() and second_operand.isdigit()):
            print('Error: Numbers must only contain digits.') 

        if len(first_operand) > 4 or len(second_operand) > 4:
            print('Error: Numbers cannot be more than four digits.')

        
        #Formatting right-alignment

        #The width is the maximum length of the two operands plus 2 
        width = max(len(first_operand), len(second_operand)) + 2  
        #Calculating how many spaces are needed
        first_line_spacing = width - len(first_operand)  
        # '123' is 3 characters long, width is 5, number of spaces needed is 
        # 5 - 3 = 2 spaces needed for alignment
'''
        '  ' + 123 = '  123' (width of 5)
                    '+  49'
'''   
        first_line = ' ' * first_line_spacing + first_operand #add the spaces and then the operand
        
        second_line_spacing = width - len(second_operand) - 1
        # 5 - 2 = 3 spaces - 1 for the operator = 2
        second_line = operator + ' ' * second_line_spacing + second_operand

        dashes = '-' * width


    return problems

print(f'\n{arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])}')
'''
        '  ' + 123 = '  123' (width of 5)
                    '+  49'
'''   

Delete all this

1 Like

This is my code now, but I’m receiving this in the console by itself:

123/n+ 49/n-----

which I’m not sure how to interpret:

def arithmetic_arranger(problems, show_answers=False):

    #1) Check if there are too many problems supplied
    if len(problems) >= 5:
        print(f'Error: Too many problems.')

    first_line = ''
    second_line = ''
    answer_line = ''
    dashes = ''

    i=0

    for problem in problems:    
        parts = problem.split() #The split() method splits the substring "problem" into a LIST called parts, default separator is any whitespace. Split once, store the result
        first_operand = parts[0]
        operator = parts[1]
        second_operand = parts[2]
        
        #Error checking
        if operator not in ['+', '-']:
            print("Error: Operator must be '+' or '-'.")

        if not (first_operand.isdigit() and second_operand.isdigit()):
            print('Error: Numbers must only contain digits.') 

        if len(first_operand) > 4 or len(second_operand) > 4:
            print('Error: Numbers cannot be more than four digits.')

        
        #Formatting right-alignment

        #The width is the maximum length of the two operands plus 2 
        width = max(len(first_operand), len(second_operand)) + 2  
        #Calculating how many spaces are needed
        first_line_spacing = width - len(first_operand)  
        # '123' is 3 characters long, width is 5, number of spaces needed is 
        # 5 - 3 = 2 spaces needed for alignment
   
        first_line = ' ' * first_line_spacing + first_operand #add the spaces and then the operand
        
        second_line_spacing = width - len(second_operand) - 1
        # 5 - 2 = 3 spaces - 1 for the operator = 2
        second_line = operator + ' ' * second_line_spacing + second_operand

        dashes = '-' * width

        #Handling the answers
        if show_answers:
            if operator == '+':
                answer = str(int(first_operand) + (second_operand))
            elif operator == '-':
                answer = str(int(first_operand) - (second_operand))
            
            answer_line = ' ' * (width - len(answer)) + answer

        #Adding spaces between the problems
        if i < len(problems) - 1:
            first_line += '    '
            second_line += '    '
            answer_line += '    '
            dashes += '    '
            i+=1
        
    if show_answers:
        final_problems = first_line + '/n' + second_line + '/n' + dashes + '/n' + answer_line
    else:
        final_problems = first_line + '/n' + second_line + '/n' + dashes

    return final_problems

print(f'\n{arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])}')

You’re getting too fancy here. Just print the result of your function:

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

I would also double-check your newline characters.

'/n'
\n

Thank you. This is my updated code. It is currently unable to pass the last two tests but the console just tells me the expected output. I’m not sure how what I have is different from the expected. Is this where the repr() function is supposed to be used?

def arithmetic_arranger(problems, show_answers=False):

    #1) Check if there are too many problems supplied
    if len(problems) > 5:
        return(f'Error: Too many problems.')

    first_line = ''
    second_line = ''
    answer_line = ''
    dashes = ''

    i=0

    for problem in problems:    
        parts = problem.split() #The split() method splits the substring "problem" into a LIST called parts, default separator is any whitespace. Split once, store the result
        first_operand = parts[0]
        operator = parts[1]
        second_operand = parts[2]
        
        #Error checking
        if operator not in ['+', '-']:
            return("Error: Operator must be '+' or '-'.")

        if not (first_operand.isdigit() and second_operand.isdigit()):
            return('Error: Numbers must only contain digits.') 

        if len(first_operand) > 4 or len(second_operand) > 4:
            return('Error: Numbers cannot be more than four digits.')

        
        #Formatting right-alignment

        #The width is the maximum length of the two operands plus 2 
        width = max(len(first_operand), len(second_operand)) + 2  
        #Calculating how many spaces are needed
        first_line_spacing = width - len(first_operand)  
        # '123' is 3 characters long, width is 5, number of spaces needed is 
        # 5 - 3 = 2 spaces needed for alignment
   
        first_line += ' ' * first_line_spacing + first_operand #add the spaces and then the operand
        
        second_line_spacing = width - len(second_operand) - 1
        # 5 - 2 = 3 spaces - 1 for the operator = 2
        second_line += operator + ' ' * second_line_spacing + second_operand

        dashes += '-' * width

        #Handling the answers
        if show_answers:


            # Calculate and format the answer
            if operator == '+':
                answer = str(int(first_operand) + int(second_operand))
            else:
                answer = str(int(first_operand) - int(second_operand))
            answer_line += ' ' * (width - len(answer)) + answer



            if operator == '+':
                answer = str(int(first_operand) + int(second_operand))
            else:
                answer = str(int(first_operand) - int(second_operand))
            
            answer_line += ' ' * (width - len(answer)) + answer

        #Adding spaces between the problems
        if i < len(problems) - 1:
            first_line += '    '
            second_line += '    '
            dashes += '     '
            i+=1
            if show_answers:
                answer_line += '   '

    #Combining lines into final output    
    if show_answers:
        final_problems = first_line + '\n' + second_line + '\n' + dashes + '\n' + answer_line
    else:
        final_problems = first_line + '\n' + second_line + '\n' + dashes

    return final_problems

print(f'\n{arithmetic_arranger(["11 + 4", "3801 - 2999", "1 + 2", "123 + 49", "1 - 9380"])}')

This is the console:

// 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(["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

Yes this is a good point to print with repr()

Also, there is a note at the end of the instructions, just before the tests. Press F12 and look for errors in the devtools browser console.

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!

1 Like

I was able to finish the project, thank you!

1 Like