Scientific Computing with Python Projects - Arithmetic Formatter

Hi,
Can someone pls help me understanding how should I solve this issue:

Code below β†’

import re
def arithmetic_arranger(problems, solver=False):
    # Principal Variables
    first_number = ""
    second_number = ""
    lines = ""
    solution_problems = ""
    string = ""

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

    # Checks
    for problem in problems:
        if (re.search("[^\s0-9.+-]", problem)):
            if (re.search("[/]", problem) or re.search("[*]", problem)):
                return "Error: Operator must be '+' or '-'."
            return "Error: Numbers must only contain digits."

        # Core FOR Loop
        problem_array = problem.split(" ")
        first_number = problem_array[0]
        operator = problem_array[1]
        second_number = problem_array[2]
        
        # Check number of digits
        if (len(first_number) >= 5 or len(second_number) >= 5):
            return "Error: Numbers cannot be more than four digits."

        # Solution
        solution = ""
        if (operator == "+"):
            solution = str(int(first_number) + int(second_number))
        elif (operator == "-"):
            solution = str(int(first_number) - int(second_number))


        length = max(len(first_number), len(second_number)) + 2
        top = str(first_number).rjust(length) + "    "
        bottom = operator + str(second_number).rjust(length - 1) + "    "
        line = ""
        result = str(solution).rjust(length)+ "    "
        for line in range(length):
            lines += "-"
     
    if solver:
     solution_problems = top + "\n" + bottom + "\n" + lines + "\n" + result + "\n"
 
        
    else:
     solution_problems = top + "\n" + bottom + "\n" + lines 
      
    return solution_problems   

Thanks!

so just to be sure, you need help figuring out why the dashed line is too long? (progressively too long?)

yes. I know it is because of +=. But I don’t know how to fix it

well, I could help you debug it but I feel that you should tackle the big problem first which is that you are not producing output the way that this exercise expects:

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

If you look at it as a horizontal series of values that need to be produced, then you may not run into the progressively longer dash issue at all.

1 Like

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