I have completed the code but all my results are not matching… can anyone tell me what is the mistake in my code?
def arithmetic_arranger(digits, show_results=False):
# Making arrangement
first_line = []
second_line = []
dashes = []
results = []
if len(digits) > 4:
return 'Error: Too many problems.'
for digit in digits:
# Split digits
parts = digit.split()
num1 = parts[0]
operator = parts[1]
num2 = parts[2]
# Valid input situations
if operator not in ['+', '-']:
return "Error: Operator must be '+' or '-'."
if not (num1.isdigit() and num2.isdigit()):
return 'Error: Numbers must only contain digits.'
if len(num1) > 4 or len(num2) > 4:
return 'Error: Numbers cannot be more than four digits.'
# Deciding width
width = max(len(num1), len(num2)) + 2
# Shaping digits in a format
first_line.append(num1.rjust(width))
second_line.append(operator + ' ' + num2.rjust(width - 2))
dashes.append('-' * width)
# Result display
if show_results:
if operator == '+':
result = str(int(num1) + int(num2))
else:
result = str(int(num1) - int(num2))
results.append(result.rjust(width))
# Combine the lines into a single output
arranged_digits ='\n' + ' '.join(first_line) +'\n' +' '.join(second_line) + '\n' +' '.join(dashes)
if show_results:
arranged_digits +='\n' +' '.join(results)
return arranged_digits
# Test the function
print(arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"], True))
my output