I do not know why my code does not pass the test cases for the show answers = false tests.
def arithmetic_arranger(problems, show_answers=False):
if len(problems) > 5:
Errorlength = 'Error: Too many problems.'
return Errorlength
problems1=''
problems2=''
midline = ''
for problem in problems:
operand = problem.split(" ")
if operand[1] not in ['+','-']:
return "Error: Operator must be '+' or '-'."
if not operand[0].isdigit() or not operand[2].isdigit():
return 'Error: Numbers must only contain digits.'
if len(operand[0]) > 4 or len(operand[2]) > 4:
return 'Error: Numbers cannot be more than four digits.'
line = ''
# Calculate the width needed for the problem
width = max(len(operand[0]), len(operand[2])) + 2
for lines in range(width):
line += '-'
# Add the formatted operands and operator to the arranged problems string
problems1 += operand[0].rjust(width) + ' '
problems2 += operand[1] + ' ' + operand[2].rjust(width - 2) + ' '
midline += line.rjust(width) + ' '
problems = problems1 + '\n' + problems2 + '\n' + midline + '\n'
sproblems = ''.join(problems)
# Remove trailing whitespace from the arranged problems string
sproblems = sproblems.rstrip()
# If show_answers is True, calculate and add the answers to the arranged problems
if show_answers:
problems += '\n'
for problem in problems:
operand[0], operand[1], operand[2] = problem.split()
if operand[1] == '+':
answer = str(int(operand[0]) + int(operand[2]))
else:
answer = str(int(operand[0]) - int(operand[2]))
width = max(len(operand[0]), len(operand[2])) + 2
problems += '-' * width + ' '
problems += answer.rjust(width) + ' '
sproblems = ' '.join(problems)
# Remove trailing whitespace from the arranged problems string
sproblems = sproblems.rstrip()
# Return the arranged problems
return sproblems
print(f'\n{arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])}')
