Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project

Tell us what’s happening:

Skip to content
Search 11,400+ tutorials

Menu
Profile
Your code was saved to the database. It will be here when you return.Close
×
Scientific Computing with Python (Beta)
Build an Arithmetic Formatter Project
Instructions
main.pyEditor
ConsoleHide the previewPreviewMove the preview to a new window and focus it
Build an Arithmetic Formatter Project
Students in primary school often arrange arithmetic problems vertically to make them easier to solve. For example, “235 + 52” becomes:

235

  • 52

Your code so far


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 Edg/131.0.0.0

Challenge Information:

Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project

Tell us what’s happening:

Failed:6. arithmetic_arranger([“3 / 855”, “3801 - 2”, “45 + 43”, “123 + 49”]) should return “Error: Operator must be ‘+’ or ‘-’.”.
Failed:9. arithmetic_arranger([“3 + 855”, “988 + 40”], True) should return 3 988\n+ 855 + 40\n----- -----\n 858 1028.
Failed:10. 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----- ------ ---- -----

Your code so far


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 Edg/131.0.0.0

Challenge Information:

Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project

Tell us what’s happening:

Failed:6. arithmetic_arranger([“3 / 855”, “3801 - 2”, “45 + 43”, “123 + 49”]) should return “Error: Operator must be ‘+’ or ‘-’.”.
Failed:9. arithmetic_arranger([“3 + 855”, “988 + 40”], True) should return 3 988\n+ 855 + 40\n----- -----\n 858 1028.
Failed:10. 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----- ------ ---- -----

Your code so far

def arithmetic_arranger(problems, show_answers=False):
    # Step 1: Check if there are too many problems
    if len(problems) > 5:
        return 'Error: Too many problems.'

    # Initialize lists to store the top row, bottom row, and dashes for each problem
    top_rows = []
    bottom_rows = []
    dashes = []
    results = []

    for problem in problems:
        # Split the problem into two operands and the operator
        parts = problem.split()
        
        if len(parts) != 3:
            continue  # Shouldn't happen in the provided tests, but handle any malformed problems
        
        num1, operator, num2 = parts
        
        # Step 2: Check if the operator is valid (either '+' or '-')
        if operator not in ('+', '-'):
            return 'Error: Operator must be "+" or "-".'
        
        # Step 3: Check if both numbers are digits and not longer than 4 digits
        if not num1.isdigit() or not num2.isdigit():
            return 'Error: Numbers must only contain digits.'
        
        if len(num1) > 4 or len(num2) > 4:
            return 'Error: Numbers cannot be more than four digits.'

        # Step 4: Calculate the result if show_answers=True
        if show_answers:
            if operator == '+':
                result = str(int(num1) + int(num2))
            elif operator == '-':
                result = str(int(num1) - int(num2))
            results.append(result)

        # Calculate the width needed for alignment (considering the largest number and operator space)
        max_len = max(len(num1), len(num2)) + 2  # Add 2 for the operator and space between numbers
        top_rows.append(num1.rjust(max_len))
        bottom_rows.append(f"{operator} {num2.rjust(max_len - 2)}")  # Adjust to ensure proper alignment
        dashes.append('-' * max_len)

    # Step 5: Combine the rows into the final formatted output
    arranged_problems = '    '.join(top_rows) + '\n' + '    '.join(bottom_rows) + '\n' + '    '.join(dashes)

    # If show_answers is True, add the results line at the bottom
    if show_answers:
        arranged_problems += '\n' + '    '.join(results)

    return arranged_problems


# Test cases

# Test 1: Regular Output without show_answers
print(f'\n{arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])}')
# Expected Output:
#    32      3801      45      123
# +  698    -    2    + 43    +  49
# ------    ------    ----    -----

# Test 2: With show_answers=True
print(f'\n{arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49", "988 + 40"], show_answers=True)}')
# Expected Output:
#    32         1      45      123      988
# -  698    - 3801    + 43    +  49    +  40
# ------    ------    ----    -----    -----
#  -666     -3800      88      172     1028

# Test 3: Invalid Operator ('/'), should return an error
print(arithmetic_arranger(["3 / 855", "3801 - 2", "45 + 43", "123 + 49"],))
# Expected Output: 'Error: Operator must be "+" or "-".'

# Test 4: Show results with show_answers=True
print(arithmetic_arranger(["3 + 855", "988 + 40"], True))
# Expected Output:
#     3      988
# +  855    +  40
# -----    -----
#   858     1028

# Test 5: More than 5 problems, should return an error
print(arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49", "988 + 40", "24 + 18"]))
# Expected Output: 'Error: Too many problems.'

# Test 6: Numbers greater than 4 digits, should return an error
print(arithmetic_arranger(["24 + 85215", "3801 - 2", "45 + 43", "123 + 49"]))
# Expected Output: 'Error: Numbers cannot be more than four digits.'

# Test 7: Numbers with non-digit characters, should return an error
print(arithmetic_arranger(["98 + 3g5", "3801 - 2", "45 + 43", "123 + 49"]))
# Expected Output: 'Error: Numbers must only contain digits.'

# Test 8: With show_answers=True and multiple problems
print(arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49", "988 + 40"], True))
# Expected Output:
#    32         1      45      123      988
# -  698    - 3801    + 43    +  49    +  40
# ------    ------    ----    -----    -----
#  -666     -3800      88      172     1028



```py

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 Edg/131.0.0.0

Challenge Information:

Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project

Welcome to the forum @J3DiM4ST3R

I went ahead and combined your posts for you. In the future, just reply to the original thread to add further updates.

Try using single quote marks.

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!

BTW, you’ll find it easier to learn Python if you switch house to "Slytherin".

Happy coding