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"])}')