Python - Arithmetic Formatter Problem

I’m not sure what’s wrong here. I’ve written code to handle the key rules for this challenge and all the tests look to be showing the correctly formatted answers, but they are not evaluating in the tests. My code is below:

def arithmetic_arranger(problems, torf=True):
  # if optional argument is true, execute code
  if torf:
    #define variables used later
    nums = ''
    dens = ''
    sums = ''
    # error when too many problems
    if len(problems) > 5:
      return 'Error: Too many problems.'
    # split problem into components
    for k in problems:
      l = (k.split(' '))
      num = l[0]
      op = l[1]
      den = l[2]
      # error when numbers are too long or non-numeric
      if len(num) > 4 or len(den) > 4:
        return 'Error: Numbers cannot be more than four digits.'
      if not num.isnumeric() or not den.isnumeric():
        return 'Error: Numbers must only contain digits.'
      # execute code if operators are correct
      if  op == '+' or op == '-':
        # set length of sum and top, bottom and line values
        length = max(len(num), len(den)) + 2
        top = str(num).rjust(length)
        bottom = op + str(den).rjust(length - 1)
        sum = ''
        for s in range(length):
          sum += '-'
        # add to the overall string
        nums += top + '    '
        dens += bottom + '    '
        sums += sum + '    '   
      else: 
        return "Error: Operator must be '+' or '-'."
    # strip out spaces to the right of the string
    nums.rstrip()
    dens.rstrip()
    sums.rstrip()

    arranged_problems = nums + '\n' + dens + '\n' + sums
    return arranged_problems

Below is the error message shown in the console.

    3      3801      45      123    
+ 855    -    2    + 43    +  49    
-----    ------    ----    -----    
F..F..
======================================================================
FAIL: test_arrangement (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/GratefulCuddlyDatasets/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: '    [23 chars]  123    \n+ 855    -    2    + 43    +  49   [35 chars]    ' != '    [23 chars]  123\n+ 855    -    2    + 43    +  49\n-----[23 chars]----'
-     3      3801      45      123    
?                                 ----
+     3      3801      45      123
- + 855    -    2    + 43    +  49    
?                                 ----
+ + 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/GratefulCuddlyDatasets/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: '   3[23 chars]  123    \n- 698    - 3801    + 43    +  49   [35 chars]    ' != '   3[23 chars]  123\n- 698    - 3801    + 43    +  49\n-----[57 chars] 172'
-    32         1      45      123    
?                                 ----
+    32         1      45      123
- - 698    - 3801    + 43    +  49    
?                                 ----
+ - 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.005s

FAILED (failures=2)

Link to my repl.it here

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36.

Challenge: Arithmetic Formatter

Link to the challenge:

you need to just use the given numbers, and display them as required, not do the calculations

Oof, is one not allowed to use format strings in this challenge? This looks tedious as all get-out.

I’m not trying to solve the calculations - just trying to format the given numbers in the correct way. It looks like they are showing formatted correctly but the FCC test is not evaluating my code as being correct. That’s the help I was asking for as I’m not sure what’s wrong with my solution.

I’m not sure. I also tried a workaround where the code would add the spaces to display the numbers in the correct places, but that showed the same errors too.

you have spaces before the \n character after the last number on a line, instead there should not be

I’m not able to tell you if there’s an error or where that would be - looks like I’m much more of a beginner than you - just wanted to say hi and thank you for posting your code as it’s helping me figure out where I was stuck!

3 Likes

Instead of stripping the empty strings like that, you can use join method with empty spaces.

nums = []
for top in tops:
    nums.append(top)

"    ".join(nums)

Implement this logic within your code.

Updated:
I saw you rstrip the end spaces but you didn’t take the return value.

Try

nums = nums.rstrip()

Also you don’t have the answer line implemented. So the test with answer will not pass

I have a far more verbose solution to this project, and it works fine if I pass the test values directly to the arithmetic_arranger method:

> # This entrypoint file to be used in development. Start by reading README.md
> from arithmetic_arranger import arithmetic_arranger
> from unittest import main
> 
> 
> print(arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"], True))
> print(arithmetic_arranger(["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]))
> print(arithmetic_arranger(["11 + 4", "3801 - 2999", "1 + 2", "123 + 49", "1 - 9380"]))
> print(arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49", "888 + 40", "653 + 87"]))
> print(arithmetic_arranger(["3 / 855", "3801 - 2", "45 + 43", "123 + 49"]))
> print(arithmetic_arranger(["24 + 85215", "3801 - 2", "45 + 43", "123 + 49"]))
> print(arithmetic_arranger(["98 + 3g5", "3801 - 2", "45 + 43", "123 + 49"]))
> print(arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49"], True))
> 
> # Run unit tests automatically
> #main(module='test_module', exit=False)

Yet if I comment out the method calls and use the test_module instead I am seeing the same errors as yourself.

My code:

def arithmetic_arranger(problems, dosum=None):

    arranged_problems = ""
    
    # Test that number of problems is within range
    if len(problems) > 5:
        arranged_problems="Error: Too many problems."
        return arranged_problems

    top = []  # Will store values for top row
    bottom = []  # Will store values for bottom row
    if dosum: allsums = []  # Will store sum values if desired
    for problem in problems:  
        pieces = problem.split()

        # Error checking
        if not pieces[0].isnumeric() or not pieces[2].isnumeric():
            arranged_problems = "Error: Numbers must only contain digits."
            return arranged_problems
        if len(pieces[0]) > 4 or len(pieces[2]) > 4:
            arranged_problems = "Error: Numbers cannot be more than four digits."
            return arranged_problems
        if pieces[1] != "+" and pieces[1] != "-":
            arranged_problems = "Error: Operator must be '+' or '-'."
            return arranged_problems

        if dosum is True: # Get sums if these are desired
            calc = 0
            if pieces[1] == "+":
                calc = int(pieces[0]) + int(pieces[2])
            elif pieces[1] == "-":
                calc = int(pieces[0]) - int(pieces[2])
            else:
                arranged_problems="Error: Operator must be '+' or '-'."
                return arranged_problems
            pieces.append(str(calc))
        
        top.append(pieces[0])  # Top values
        bottom.append((pieces[1], pieces[2]))  # Bottom values
        if dosum: allsums.append(pieces[3])  # Sum values

    # Determine length of each sum
    alltop_lengths = []
    allbottom_lengths = []
    actual_lengths = []
    
    for top_length in top:
        alltop_lengths.append(len(top_length))
    
    for bottom_length in bottom:
        allbottom_lengths.append(len(bottom_length[1]))
    
    for count in range(0, len(alltop_lengths)):  # We could also use allbottom_lengths here
        if alltop_lengths[count] >= allbottom_lengths[count]:
            actual_lengths.append(alltop_lengths[count])         
        else:
            actual_lengths.append(allbottom_lengths[count])
        
        actual_length_int = (int(actual_lengths[count])) + 2  # Add operator plus one space
        actual_lengths[count] = actual_length_int

    # Build string
    
    # Top row of operands
    count = 0
    for top_string in alltop_lengths:
        space_length = actual_lengths[count] - top_string
        spacing = ""
        for spacecount in range(1, space_length+1):  # I suspect there is a better way of doing this
            spacing = spacing + " "
        arranged_problems = arranged_problems + spacing
        arranged_problems = arranged_problems + top[count]
        arranged_problems = arranged_problems + "    "
        count = count + 1
    arranged_problems = arranged_problems.rstrip()
    arranged_problems = arranged_problems + "\n"

    # Second row of operators and operands
    count = 0
    for bottom_string in allbottom_lengths:
        arranged_problems = arranged_problems + bottom[count][0] + " "
        space_length = (actual_lengths[count] - 2) - bottom_string
        if space_length > 0:
            spacing = ""
            for spacecount in range(1, space_length+1):
                spacing = spacing + " "
            arranged_problems = arranged_problems + spacing
        arranged_problems = arranged_problems + bottom[count][1]
        arranged_problems = arranged_problems + "    "
        count = count + 1
    arranged_problems = arranged_problems.rstrip()
    arranged_problems = arranged_problems + "\n"

    # Dashes row
    for dashes_length in actual_lengths:
        for dashcount in range (1, dashes_length+1):
            arranged_problems = arranged_problems + "-"
        arranged_problems = arranged_problems + "    "
    arranged_problems = arranged_problems.rstrip()
    arranged_problems = arranged_problems + "\n"

    # Sums row
    if dosum:
        count = 0
        for thissum in allsums:
            space_length = actual_lengths[count] - len(thissum)
            for spacecount in range (1, space_length+1):
                arranged_problems = arranged_problems + " "
            arranged_problems = arranged_problems + thissum
            arranged_problems = arranged_problems + "    "
            count = count + 1
        arranged_problems = arranged_problems.rstrip()
        arranged_problems = arranged_problems + "\n"

    return arranged_problems
1 Like

look at the errors, the diff scheme shows you where you have extra characters - it’s the easiest way if you have extra spaces or \n and where

I think I have figured it out, the trick is not to add “\n” to the end of the last lineof the output string.

PS C:\Users\Craig\Python\FCCProjects\Scientific Computing with Python\Arithmetic Formatter> & C:/Users/Craig/AppData/Local/Programs/Python/Python39/python.exe "c:/Users/Craig/Python/FCCProjects/Scientific Computing with Python/Arithmetic Formatter/main.py"
......
----------------------------------------------------------------------
Ran 6 tests in 0.004s

OK

A post was split to a new topic: Python arithmetic formatter

Can you explain this with code, which line exactly you are referring to?

In the output you are formatting a number of lines, basically the very last line that you output should not have a ‘\n’ at the end of it.