Here is my code so far. I can not make the operator have only one space with the denominator though. It will always be two spaces between the denominator and operator even when the denominator is longer than the numerator, and somehow I can not find the bug. Everything else is fully functional.
def arithmetic_arranger(problems, option=False):
numerators = ''
denominators = ''
sums = ''
results = ''
for number in problems:
num = number.split(" ")
numerator = num[0]
operator = num[1]
denominator = num[2]
try_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for separate in numerator and denominator:
if separate not in try_list:
return 'Error: Numbers must only contain digits.'
if operator == '+' or operator == '-':
length = max(len(numerator), len(denominator + operator)) + 2
top = numerator.rjust(length)
bottom = str(operator) + str(denominator.rjust(length - 1))
numerators += top + ' ' * 4
denominators += bottom + ' ' * 4
sum = ''
if len(numerator) >= 5 or len(denominator) >= 5:
return 'Error: Numbers cannot be more than four digits.'
if len(problems) > 5:
return 'Error: Too many problems.'
for lines in range(length):
lines = '-'
sum += lines
sums += sum.rjust(length - 1) + ' ' * 4
result = ''
if option:
r = eval(numerator + operator + denominator)
r = str(r)
result += r
results += result.rjust(length) + ' ' * 4
else:
return "Error: Operator must be '+' or '-'."
return numerators + '\n' + denominators + '\n' + sums + '\n' + results
print(arithmetic_arranger(["32 + 8", "1 - 3801", "45 + 43", "123 + 49"], True))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36 OPR/72.0.3815.450
.
Challenge: Arithmetic Formatter
Link to the challenge: