Python Arithmetic Formatter Certification Project

Hi All,

This is my first post to the forums after using FCC for some time. I’ve viewed similar issues but haven’t found any similar enough to my own.

When I run my code in Visual Studio Code, all of the tests pass. However, when I copy the code over to the repl.it link, two tests fail. I think the extra "+ " sign at the start of the first line in the error output has something to with the problem, but I can’t figure out where it’s coming from.

My repl.it link:

repl.it/repls/DrearyQuirkyWrapper#arithmetic_arranger.py

My code:

def arithmetic_arranger(problems, answers=False):

    # These are used later
    first_line = ""
    second_line = ""
    dash_line = ""
    answer_line = ""

    # This is referenced in the loop, but is important to define outside of the loop
    number_of_problems_left = len(problems)

    # These are used later
    formatted_problems = []

    # Too many problems requirement
    if len(problems) > 5:
        return "Error: Too many problems."

    # "problems" is a list of strings
    for problem in problems:

        # For each loop iteration of the loop, there's one less problem to check
        number_of_problems_left = number_of_problems_left - 1
        
        # Break up each problem string
        new_problem = problem.split()
        first_operand = new_problem[0]
        operator = new_problem[1]
        second_operand = new_problem[2]

        # Only digits requirement
        if (first_operand.isdigit() != True) or (second_operand.isdigit() != True):
            return "Error: Numbers must only contain digits."
        # Only 4 digits requirement
        if (len(first_operand) > 4) or (len(second_operand) > 4):
            return "Error: Numbers cannot be more than four digits."
        # Only "+" or "-" requirement
        if (operator != "+") and (operator != "-"):
            return "Error: Operator must be '+' or '-'."
        
        # Initialize "answer", used directly below
        answer = ""

        # Does the actual arithmetic
        if operator == "+":
            answer = int(first_operand) + int(second_operand)
        else: # operator must be "-"
            answer = int(first_operand) - int(second_operand)
        
        # This defines how many dashes there should be at the bottom of each problem
        width_of_problem = max(len(first_operand), len(second_operand)) + 2
        
        # "rjust" will right-align a string, using a space as the default fill character
        # Formatting of each problem is here
        first_line += str(first_operand.rjust(width_of_problem))
        second_line += str(operator + second_operand.rjust(width_of_problem - 1))
        dash_line += str("-" * width_of_problem)
        answer_line += str(answer).rjust(width_of_problem)

        if number_of_problems_left > 0:
            column_width = "    "
            first_line += column_width
            second_line += column_width
            dash_line += column_width
            answer_line += column_width

        if answers == True:
            formatted_problems = (first_line + "\n" + second_line + "\n" + dash_line + "\n" + answer_line)
        else:
            formatted_problems = (first_line + "\n" + second_line + "\n" + dash_line)
    
    return formatted_problems

# arithmetic_arranger(["4 + 46", "434 - 56", "5345 + 1"], True)

My errors:

Error: Operator must be '+' or '-'.
F..F..
======================================================================
FAIL: test_arrangement (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/5omqa6z5068/test_module.py", line 10, in test_arrangement
    self.assertEqual(actual, expected, 'Expected different output when calling "arithmetic_arranger()" with ["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]')
AssertionError: "Error: Operator must be '+' or '-'." != '    3      3801      45      123\n+ 855 [56 chars]----'
- Error: Operator must be '+' or '-'.
+     3      3801      45      123
+ 855    -    2    + 43    +  49
-----    ------    ----    -----
 : Expected different output when calling "arithmetic_arranger()" with ["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]

======================================================================
FAIL: test_solutions (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/5omqa6z5068/test_module.py", line 39, in test_solutions
    self.assertEqual(actual, expected, 'Expected solutions to be correctly displayed in output when calling "arithmetic_arranger()" with arithemetic problems and a second argument of `True`.')
AssertionError: "Error: Operator must be '+' or '-'." != '   32         1      45      123\n- 698 [90 chars] 172'
- Error: Operator must be '+' or '-'.
+    32         1      45      123
- 698    - 3801    + 43    +  49
-----    ------    ----    -----
 -666     -3800      88      172
 : Expected solutions to be correctly displayed in output when calling "arithmetic_arranger()" with arithemetic problems and a second argument of `True`.

----------------------------------------------------------------------
Ran 6 tests in 0.002s

FAILED (failures=2)
1 Like

here it’s saying you are returning an error when you should return the arranged numbers

and same thing for the other error

I’ve done all five Python for Scientific Computing and the first two Data Analysis with Python challenges, and getting the string formatting right in this and the budget calc challenges was for me the hardest part of any of the projects so far, which judging from the output here could be the issue.

I found Visual Studio Express was the best IDE for interpreting the string based test module output for the projects, which may help here if you have it available. If you use the debugger you can see the expected result with the actual result underneath it which helps pin down where those missing and extraneous spaces and newlines are.

Hi there, thanks so much for taking a look. That’s helpful. I guess it’s getting the error because of the “+” sign to the left of the first “3” in the first line, which shifts everything over two spaces. I just don’t know where that “+” sign is coming from. I’ll keep debugging.

Hi there, thanks so much for taking a look. Yes, the string formatting in this one has definitely been a challenge! I’ll take a look at Visual Studio Express for debugging, appreciate the recommendation.

no, actually the + indicate that that line should be there but isn’t

the line starting with - indicates that the line is present but shouldn’t be

this is the code:


        # Only "+" or "-" requirement
        if (operator != "+") and (operator != "-"):
            return "Error: Operator must be '+' or '-'."

your code doesn’t match the comment, one of the two is saying the wrong thing

Hmm… I double-checked to make sure I’m comparing a string (“operator”) to a string ("+" or “-”). The logic seems correct as well, since "Error: Operator must be '+' or '-'." should only return if the “operator” doesn’t match “+” or “-”. The error message itself is copy/pasted from the README, so that should match, too.

are you sure this is the logic operator that say “this OR that”?

Aaaaaaaah, I see. The double conditional statement was off. Thank you. Now I have:

    # Only "+" or "-" requirement
    if (operator != "+") or (operator != "-"):
      return "Error: Operator must be '+' or '-'."

I ran it again with the correction, but string formatting still seems to be off:

======================================================================
FAIL: test_arrangement (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/EnergeticAttractiveUsername/test_module.py", line 10, in test_arrangement
    self.assertEqual(actual, expected, 'Expected different output when calling "arithmetic_arranger()" with ["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]')
AssertionError: "Error: Operator must be '+' or '-'." != '    3      3801      45      123\n+ 855 [56 chars]----'
- Error: Operator must be '+' or '-'.
+     3      3801      45      123
+ 855    -    2    + 43    +  49
-----    ------    ----    -----
 : Expected different output when calling "arithmetic_arranger()" with ["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]

======================================================================
FAIL: test_solutions (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/EnergeticAttractiveUsername/test_module.py", line 39, in test_solutions
    self.assertEqual(actual, expected, 'Expected solutions to be correctly displayed in output when calling "arithmetic_arranger()" with arithemetic problems and a second argument of `True`.')
AssertionError: "Error: Operator must be '+' or '-'." != '   32         1      45      123\n- 698 [90 chars] 172'
- Error: Operator must be '+' or '-'.
+    32         1      45      123
- 698    - 3801    + 43    +  49
-----    ------    ----    -----
 -666     -3800      88      172
 : Expected solutions to be correctly displayed in output when calling "arithmetic_arranger()" with arithemetic problems and a second argument of `True`.

----------------------------------------------------------------------
Ran 6 tests in 0.004s

FAILED (failures=2)

can you post your repl link?

Sure, here it is: https://repl.it/repls/TintedSoggyFlash#arithmetic_arranger.py

It’s strange to me because when I copy everything over to a local repo on my personal machine and run “main.py”, all of the tests pass, unlike what happens with the repl link.

now in all cases your function just return None - I’m AFK, later I will look into it with more attention

All of your return statements are like this first one:

  # Too many problems requirement
  if len(problems) > 5:
    return print("Error: Too many problems.")

You need to return the string only. As this is, you are returning whatever the return value of print() is, which from the tests, appears to be None, according to your tests on repl.it.

Ah, man! I thought that would be it. I had been using the print statements to test in VSC, so it makes sense to omit them in the repl.it. Unfortunately, it seems like the same two errors persist. Updated repl.it link: https://repl.it/repls/TintedSoggyFlash#arithmetic_arranger.py

There’s one left:

  return print(formatted_problems)

Fix that and it works.

!! That did it! Wow, thank you so much. This was driving me crazy the past few days.
I’ve learned a lot through this challenge. My first experience with the forums has been amazing. Truly appreciate the help and support.