Tell us what’s happening:
Describe your issue in detail here.
Your code so far
def arithmetic_arranger(problems, show_answers=False):
if len(problems) > 5:
return "Error: Too many problems."
arranged_problems = ""
for problem in problems:
operand1, operator, operand2 = problem.split()
if operator not in ['+', '-']:
return "Error: Operator must be '+' or '-'."
if not operand1.isdigit() or not operand2.isdigit():
return "Error: Numbers must only contain digits."
if len(operand1) > 4 or len(operand2) > 4:
return "Error: Numbers cannot be more than four digits."
max_width = max(len(operand1), len(operand2))
line1 = operand1.rjust(max_width + 2)
line2 = operator + ' ' + operand2.rjust(max_width)
line3 = '-' * (max_width + 2)
arranged_problems += line1 + ' '
arranged_problems += line2 + ' '
arranged_problems += '\n' + line3 + ' '
if show_answers:
arranged_problems += '\n'
for problem in problems:
operand1, operator, operand2 = problem.split()
if operator == '+':
result = str(int(operand1) + int(operand2))
else:
result = str(int(operand1) - int(operand2))
max_width = max(len(operand1), len(operand2), len(result))
line4 = result.rjust(max_width + 2)
arranged_problems += line4 + ' '
return arranged_problems.strip()
# Test the function
print(arithmetic_arranger(["3801 - 2", "123 + 49"]))
print(arithmetic_arranger(["1 + 2", "1 - 9380"]))
print(arithmetic_arranger(["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]))
print(arithmetic_arranger(["11 + 4", "3801 - 2999", "1 + 2", "123 + 49", "1 - 9380"]))
print(arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49", "888 + 40", "653 + 87"]))
print(arithmetic_arranger(["3 / 855", "3801 - 2", "45 + 43", "123 + 49"]))
print(arithmetic_arranger(["24 + 85215", "3801 - 2", "45 + 43", "123 + 49"]))
print(arithmetic_arranger(["98 + 3g5", "3801 - 2", "45 + 43", "123 + 49"]))
print(arithmetic_arranger(["3 + 855", "988 + 40"], True))
print(arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49", "988 + 40"], True))
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Safari/605.1.15
Challenge Information:
Scientific Computing with Python Projects - Arithmetic Formatter