###### https://www.freecodecamp.org/learn/scientific-computing-with-python/scientific-computing-with-python-projects/arithmetic-formatter ########### arithmetic_arranger.py #####
import random, string
import operator
operator_functions = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
def arithmetic_arranger(problems, answer=None):
opr1 = ''
opr2 = ''
opr3 = ''
opr4 = ''
for i in range(len(problems)):
problem = problems[i].split()
if len(problem[0]) > 4 or len(problem[2]) > 4:
return 'Error: Numbers cannot be more than four digits.'
elif any(c.isalpha() for c in problem[0]) == True or any(c.isalpha() for c in problem[2]) == True:
return 'Error: Numbers must only contain digits.'
elif len(problems) > 5:
return 'Error: Too many problems.'
elif problem[1] not in operator_functions or problem[1] == '*' or problem[1] == '/':
return "Error: Operator must be '+' or '-'."
else:
nl = '\n'
u = max(len(problem[0]), len(problem[2]))
opr1 = opr1 + f'{problem[0].rjust(u + 2)}' + " "
opr2 = opr2 + f'{problem[1].ljust(u + 2 - len(problem[2]))}{problem[2].ljust(len(problem[2])+4)}'
opr3 = opr3 + f'{("-" * (u + 2)).ljust(u+6)}'
if answer is True:
if problem[1] == '+':
ans = int(problem[0]) + int(problem[2])
elif problem[1] == '-':
ans = int(problem[0]) - int(problem[2])
ans = str(ans)
opr4 = opr4 + f'{ans.rjust(u + 2)}' + " "
return f'{opr1}{nl}{opr2}{nl}{opr3}{nl}{opr4}'
return f'{opr1}{nl}{opr2}{nl}{opr3}'
print(arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49"], True))