FCC - Arithmetic Formatter Project - Python Project

Hi all, please find my solution below, which I had originally drafted whilst working on it with IntelliJ IDE.

At first, I was a bit confused, as it had mentioned returning errors, so I raised them as errors rather than actually returning the values (as seen in the code).

Is the return of the errors simply so that the program can actually see the responses? As I believe that raising an error would instead make a lot more sense, but I’m completely new to coding, so apologies if I’m making the wrong assumption and would love to be corrected! Also, if you have any tips in regards to coding practice which I had not applied well, please do let me know! One thing I can probably name right off the bat was renaming “i” as probs and “i_values” to something like “i_problems”. Naming is… definitely a struggle during the actual coding process.

Just as a reminder: for my actual project submission, I had modified the below code from “raise Exception” to “return”.

def arithmetic_arranger(problems, show_answers=False):


    # Check for the length of number of problems
    if len(problems) > 5:
        raise Exception("Error: Too many problems.")

    # Create lists for all lines of the problem
    operand1 = []
    operand2 = []
    line_list = []
    results_list = []

    # Cycle through each list item to analyse and segregate the information out
    for i in problems:
        val_i = lambda a : int(i_values[a])
        i_values = i.split()
        length = max(len(i_values[0]), len(i_values[2]))

        # Create checks for operator, digit length and that they are numbers
        if i_values[1] not in ("+", "-"):
            print(i_values[1] == "+" or i_values[1] == "-")
            raise Exception("Error: Operator must be '+' or '-'.")

        if length > 4:
            raise Exception("Error: Numbers cannot be more than four digits.")

        if not(i_values[0].isnumeric() and i_values[2].isnumeric()):
            raise Exception("Error: Numbers must only contain digits.")

        # Once all items from the list have been split apart, format correctly using f-strings and place into
        # their respective lists.
        operand1.append(f'{val_i(0):{length + 2}}')
        operand2.append(f'{i_values[1]} {val_i(2):{length}}')
        line_list.append("-" * (length + 2))

        # Do the computations based the operator provided.
        if i_values[1] == "+":
            num = val_i(0) + val_i(2)
            results_list.append(f'{num:{length + 2}}')

        elif i_values[1] == "-":
            num = val_i(0) - val_i(2)
            results_list.append(f'{num:{length + 2}}')

    # Now that we have all the items, combine them into individual strings.
    string1 = "    ".join(operand1)
    string2 = "    ".join(operand2)
    line_string = "    ".join(line_list)
    results_string = "    ".join(results_list)

    # Check for whether we want answers to be seen or not and return the response accordingly.
    if not show_answers:
        return (f'{string1}\n{string2}\n{line_string}')
    else:
        return (f'{string1}\n{string2}\n{line_string}\n{results_string}')
    # return problems

print(f'\n{arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49", "888 + 40", "653 + 87"], True)}')
# print(f'\n{arithmetic_arranger(["32 + 698", "3801 - 2"])}')

I think the error returning was due to not introducing raise in the courses before this project.


  • Naming of the variables. line_list, results_list, i, val_i, i_values, length, string1, string2, line_string, resutls_string all could use a more descriptive, or improved names.
  • Raising Exception. Exception is a very broad… exception, if you look at the hierarchy of the built-in exceptions (Built-in Exceptions — Python 3.13.7 documentation), the Exception is almost at the top there. Somebody wanting to handle exception raised by your arithmetic_arranger would need to catch the Exception with try/except. Meaning that various other sub-exceptions, which you might not want to catch (ie. something completely unrelated like OSError or MemoryError), also would be caught.
  • val_i lambda. I think adding function (and lambda function especially) for this is adding more complexity than needed. Simpler and easier would be converting them to int just once and then use that.
  • Repetition in the if/else. If some parts are repeated it means there might be a way to extract part that’s not differing outside of the if/else.
    • if not show_answers:
          return (f'{string1}\n{string2}\n{line_string}')
      else:
          return (f'{string1}\n{string2}\n{line_string}\n{results_string}')
      
    •     if i_values[1] == "+":
              num = val_i(0) + val_i(2)
              results_list.append(f'{num:{length + 2}}')
      
          elif i_values[1] == "-":
              num = val_i(0) - val_i(2)
              results_list.append(f'{num:{length + 2}}')
      
  • Indexing like i_values[0], i_values[1], i_values[2], in multiple places. It would be much more clear if these values also would have specific names. Take a look at the co-called tuple (or list) unpacking in python.
  • Comments - usually comments that describes what is happening in a code that’s not complicated are obsolete, as the same can be learned after reading the code itself. Comments definitely can be used when there’s some information that would give some context as in why something is done that way, or why something is happening.
1 Like

Thank you so much for the useful feedback! I’ll definitely take these on board when writing up code, especially in the parts of not overcomplicating things as well as reducing repetition.

As for the try / except, I’ll definitely look into do that for next time and specifying further what each exception is rather than the broad term.

Thanks again for taking the time to respond!

1 Like