Arithmetic Formatter: String Formatting issues

I am having issues with the string formatting. I’m not able to figure out how to do that. I trying the python string padding but there is still something which I’m not catching that will solve my problem.

Here is my code:

def arithmetic_arranger(problems, display_result= False):

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

    first_operand = []
    operator = []
    second_operand = []
    result = []

    for eq in problems:
        eq_splitted = eq.split()


        if not eq_splitted[0].isnumeric():
            return "Error: Numbers must only contain digits."

        if eq_splitted[1] not in ["+", "-"]:
            return "Error: Operator must be '+' or '-'."

        if len(eq_splitted[2]) > 4 or len(eq_splitted[2]) > 4:
            return "Error: Numbers cannot be more than four digits."


        first_operand.append(eq_splitted[0])
        operator.append(eq_splitted[1])
        second_operand.append(eq_splitted[2])
        result.append(eval(eq))

    # string formatting and arrangements in the expected format.
    if display_result:

        first_line = ""
        second_line = ""
        third_line = ""
        fourth_line = ""

        for i in range(len(first_operand)):
            first_line += "{:>4}".format(first_operand[i])+" "*4
            second_line += "{}{:>3}".format(operator[i], second_operand[i])+" "*4
            third_line += "{}".format("-"*5)+" "*4
            fourth_line += "{:>4}".format(result[i])+" "*4

            arrng = first_line+"\n"+second_line+"\n"+third_line+"\n"+fourth_line



        return arrng

    else:
        first_line = ""
        second_line = ""
        third_line = ""
        fourth_line = ""      # result of the operation of every equation!

        for i in range(len(first_operand)):
            first_line += "{:>4}".format(first_operand[i])+" "*4
            second_line += "{}{:>3}".format(operator[i], second_operand[i])+" "*4
            third_line += "{}".format("-"*5)+" "*4

            arrng = first_line+"\n"+second_line+"\n"+third_line

        return arrng


    #print(arranged_problems)



print(arithmetic_arranger(["32 + 6", "1 - 2", "45 + 43", "123 + 2249"], True))
print("\n")
print(arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"]))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.37

Challenge: Arithmetic Formatter

Link to the challenge:

Do you get specific errors?
Can you post a link to your solution, so we could run it and see what happens?

@Brain150 , below is the output I’m getting, all I want it to be formatted as its expected.

 32       1      45     123    
+  6    -  2    + 43    +2249    
-----    -----    -----    -----    
  38      -1      88    2372    


  32       1    9999     523    
+  8    -3801    +9999    - 49    
-----    -----    -----    -----

Take a look at your results below ( - is your result, + is the desired outcome and ? are the differences).

-    3    3801      45     123    
?                             ----
+     3      3801      45      123
? +    ++                +
- +855    -  2    + 43    + 49    
?                             ----
+ + 855    -    2    + 43    +  49
?  +          ++              +
- -----    -----    -----    -----    
+ -----    ------    ----    ----- 
-   32       1      45     123    
?                             ----
+    32         1      45      123
? +           ++         +
- -698    -3801    + 43    + 49    
?                              ----
+ - 698    - 3801    + 43    +  49
?  +        +                 +
- -----    -----    -----    -----    
+ -----    ------    ----    -----
- -666    -3800      88     172    
?                              ----
+  -666     -3800      88      172
? +    +                 +

So there are too many spaces at the end of the lines, which is easily solved by stripping them off.
A bit harder are the lengths of the other lines (all of them, operands, result and dash line), they need to be dependent on whichever is the longest.

Can you add that to your code and see what is the result?
This is really the hardest part of this challenge, so you are almost there! :+1:t4:

Thanks for you inputs @Brain150 .
It seems I solved the problem but I have no idea why the code is working on my machine but failing on replt.it.

Here is the copy of that code!

def arithmetic_arranger(problems, display_result= False):

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

    first_operand = []
    operator = []
    second_operand = []
    result = []

    for eq in problems:
        eq_splitted = eq.split()


        if not eq_splitted[0].isnumeric():
            return "Error: Numbers must only contain digits."

        if eq_splitted[1] not in ["+", "-"]:
            return "Error: Operator must be '+' or '-'."

        if len(eq_splitted[2]) > 4 or len(eq_splitted[2]) > 4:
            return "Error: Numbers cannot be more than four digits."


        first_operand.append(eq_splitted[0])
        operator.append(eq_splitted[1])
        second_operand.append(eq_splitted[2])
        result.append(eval(eq))

    # string formatting and arrangements in the expected format.
    if display_result:

        first_line = ""
        second_line = ""
        third_line = ""
        fourth_line = ""

        for i in range(len(first_operand)):
            first_line += first_operand[i].rjust(max(len(first_operand[i]), len(second_operand[i]))+2)+" "*4
            second_line += operator[i]+" "+second_operand[i].rjust(max(len(first_operand[i]), len(second_operand[i])))+" "*4
            third_line += "-" * (max(len(first_operand[i]), len(second_operand[i]))+2)+" "*4
            fourth_line += str(result[i]).rjust(max(len(first_operand[i]), len(second_operand[i]))+2)+" "*4

            arranged_problems = first_line+"\n"+second_line+"\n"+third_line+"\n"+fourth_line



        return arranged_problems

    else:
        first_line = ""
        second_line = ""
        third_line = ""
        fourth_line = ""      # result of the operation of every equation!

        # for i in range(len(first_operand)):
        #     first_line += "{:>4}".format(first_operand[i])+" "*4
        #     second_line += "{}{:>3}".format(operator[i], second_operand[i])+" "*4
        #     third_line += "{}".format("-"*5)+" "*4
        #
        #     arrng = first_line+"\n"+second_line+"\n"+third_line


        for i in range(len(first_operand)):
            #print(first_operand[i], second_operand[i])
            first_line += first_operand[i].rjust(max(len(first_operand[i]), len(second_operand[i]))+2)+" "*4
            second_line += operator[i]+" "+second_operand[i].rjust(max(len(first_operand[i]), len(second_operand[i])))+" "*4
            third_line += "-" * (max(len(first_operand[i]), len(second_operand[i]))+2)+" "*4

            arranged_problems = first_line+"\n"+second_line+"\n"+third_line

        return arranged_problems


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

Output:

![output|690x249](upload://1AbO7Uq18YwdatqzkZsGWyXO6Zk.jpeg)

That looks much better :smiley:
Did you see the 1 Error and 2 Fail messages on replit?
It works on your machine because you test only numeric operands, try to replace the 2nd operand of the numbers with a letter and it will stop (this is what the Error tells you).

For the Fails: you solved the alignment, now the extra spaces at the end of the lines are still there. You’re done once you strip those off.

-     3      3801      45      123    
?                                 ----
+     3      3801      45      123
- + 855    -    2    + 43    +  49    
?                                 ----
+ + 855    -    2    + 43    +  49
- -----    ------    ----    -----    ?                                 ----
+ -----    ------    ----    ----- 
-    32         1      45      123    
?                                 ----
+    32         1      45      123
- - 698    - 3801    + 43    +  49    
?                                 ----
+ - 698    - 3801    + 43    +  49
- -----    ------    ----    -----    
?                                 ----
+ -----    ------    ----    -----
-  -666     -3800      88      172    ?                                 ----
+  -666     -3800      88      172 

Good luck!

@Brain150 , I actually have solved the previous Issue before your response arrived and now I ran into another one. Could you please again help to point out what’s wrong.

def arithmetic_arranger(problems, display_result= False):

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

    first_operand = []
    operator = []
    second_operand = []
    result = []

    for eq in problems: #["98 + 3g5", "3801 - 2", "45 + 43", "123 + 49"]
        eq_splitted = eq.split()


        if not (eq_splitted[0].isnumeric() and eq_splitted[2].isnumeric()):
            return "Error: Numbers must only contain digits."

        if eq_splitted[1] not in ["+", "-"]:
            return "Error: Operator must be '+' or '-'."

        if len(eq_splitted[2]) > 4 or len(eq_splitted[2]) > 4:
            return "Error: Numbers cannot be more than four digits."


        first_operand.append(eq_splitted[0])
        operator.append(eq_splitted[1])
        second_operand.append(eq_splitted[2])
        result.append(eval(eq))

    # string formatting and arrangements in the expected format.
    if display_result:

        first_line = ""
        second_line = ""
        third_line = ""
        fourth_line = ""

        for i in range(len(first_operand)):
            first_line += first_operand[i].rjust(max(len(first_operand[i]), len(second_operand[i]))+2)+" "*4
            second_line += operator[i]+" "+second_operand[i].rjust(max(len(first_operand[i]), len(second_operand[i])))+" "*4
            third_line += "-" * (max(len(first_operand[i]), len(second_operand[i]))+2)+" "*4
            fourth_line += str(result[i]).rjust(max(len(first_operand[i]), len(second_operand[i]))+2)+" "*4

            arranged_problems = first_line+"\n"+second_line+"\n"+third_line+"\n"+fourth_line



        return arranged_problems

    else:
        first_line = ""
        second_line = ""
        third_line = ""
        fourth_line = ""      # result of the operation of every equation!

        # for i in range(len(first_operand)):
        #     first_line += "{:>4}".format(first_operand[i])+" "*4
        #     second_line += "{}{:>3}".format(operator[i], second_operand[i])+" "*4
        #     third_line += "{}".format("-"*5)+" "*4
        #
        #     arrng = first_line+"\n"+second_line+"\n"+third_line


        for i in range(len(first_operand)):
            #print(first_operand[i], second_operand[i])
            first_line += first_operand[i].rjust(max(len(first_operand[i]), len(second_operand[i]))+2)+" "*4
            second_line += operator[i]+" "+second_operand[i].rjust(max(len(first_operand[i]), len(second_operand[i])))+" "*4
            third_line += "-" * (max(len(first_operand[i]), len(second_operand[i]))+2)+" "*4

            arranged_problems = first_line+"\n"+second_line+"\n"+third_line

        return arranged_problems

the error now which I am getting is from the test.py file.

python main.py
   32      3801      45      123    
+ 698    -    2    + 43    +  49    
-----    ------    ----    -----    
F..F..
======================================================================
FAIL: test_arrangement (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-8/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/boilerplate-arithmetic-formatter-8/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 arithmetic problems and a second argument of `True`.')
AssertionError: '   3[23 chars]  123    \n- 698    - 3801    + 43    +  49   [73 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    ?                                 ----
+  -666     -3800      88      172 : Expected solutions to be correctly displayed in output when calling "arithmetic_arranger()" with arithmetic problems and a second argument of `True`.

----------------------------------------------------------------------
Ran 6 tests in 0.015s

FAILED (failures=2)

Gosh, I am just not able to understand what the heck is wrong with my code…

Hey!
The problem is that there are white spaces at the end of each line.
There is a method that fixes this.

@MarcosSouza , Thanks a ton mate, that really helped and all the tests ran successfully.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.