Hello guys,
I have just finished the arithematic formatter challenge. I have tried to modularise the code and tried to write it in optimised way. Can someone please suggest me some improvements/optimisation in my code
Here is my code
def add(elements,display_results):
#global output_string, first_row, second_row, third_row, fourth_row
problem_length = max(len(elements[0]),len(elements[2]))
arithmetic_arranger.first_row+=elements[0].rjust(problem_length+2) + " "
arithmetic_arranger.second_row+="+ "+(elements[2]).rjust(problem_length) + " "
arithmetic_arranger.third_row+='-'*(problem_length+2)+ " "
if display_results:
arithmetic_arranger.fourth_row+=str(int(elements[0])+int(elements[2])).rjust(problem_length+2)+" "
def substract(elements,display_results):
#global output_string, first_row, second_row, third_row, fourth_row
problem_length = max(len(elements[0]),len(elements[2]))
arithmetic_arranger.first_row+=elements[0].rjust(problem_length+2) + " "
arithmetic_arranger.second_row+="- "+(elements[2]).rjust(problem_length) + " "
arithmetic_arranger.third_row+='-'*(problem_length+2) + " "
if display_results:
arithmetic_arranger.fourth_row+=str(int(elements[0])-int(elements[2])).rjust(problem_length+2)+ " "
def arithmetic_arranger(problems,display_results=None):
output_string=""
arithmetic_arranger.first_row=""
arithmetic_arranger.second_row=""
arithmetic_arranger.third_row=""
arithmetic_arranger.fourth_row=""
if len(problems)>5:
return "Error: Too many problems."
else:
for problem in problems:
elements=problem.split()
if not elements[0].isnumeric() or not elements[2].isnumeric():
return "Error: Numbers must only contain digits."
if len(elements[0])>4 or len(elements[2])>4:
return "Error: Numbers cannot be more than four digits."
if '+' in problem:
add(elements,display_results)
elif '-' in problem :
substract(elements,display_results)
else:
return "Error: Operator must be '+' or '-'."
if display_results:
output_string = arithmetic_arranger.first_row.rstrip() + "\n" +arithmetic_arranger.second_row.rstrip() +"\n"+arithmetic_arranger.third_row.rstrip()+"\n"+arithmetic_arranger.fourth_row.rstrip()
else:
output_string = arithmetic_arranger.first_row.rstrip() + "\n" +arithmetic_arranger.second_row.rstrip() +"\n"+arithmetic_arranger.third_row.rstrip()
# print(output_string)
return(output_string)