Tell us what’s happening:
Hello. I am not the most experienced coder, and I know there are more efficient ways to execute this project, but I am sure my code meets the requirements and the tests are still counting as incorrect. How can I fix this? Do I need to rewrite the code using specific commands?
Thanks so much!
Your code so far
def arithmetic_arranger(problems, show_answers=False):
#Error message for too many problems
if len(problems) > 5:
print('Error: Too many problems.')
return
operations = []
#list of all operations
for problem in problems:
operation = problem.split(' ')[1]
operations.append(operation)
#print(operations)
#Error message for invalid operation
for operation in operations:
if operation != '+' and operation != '-':
print("Error: Operator must be '+' or '-'.")
return
numbers = []
#list of all operands
#throws error if number not a digit
for problem in problems:
num1 = problem.split(' ')[0]
num2 = problem.split(' ')[2]
if not num1.isdigit():
print('Error: Numbers must only contain digits.')
return
if not num2.isdigit():
print('Error: Numbers must only contain digits.')
return
numbers.append(int(num1))
numbers.append(int(num2))
#print(numbers)
#error message for long numbers
for number in numbers:
if len(str(number)) > 4:
print('Error: Numbers cannot be more than four digits.')
return
top_row = ''
bottom_row = ''
dashes = ''
answers = ''
#formatting top line
#even index on top
for i in range(0,len(numbers),2):
space_width = max(len(str(numbers[i])),len(str(numbers[i+1])))+2
top_row += str(numbers[i]).rjust(space_width)
top_row += ' '
dashes += '-' * space_width
dashes += ' '
j=0
for k in operations:
if k=='+':
space_width = max(len(str(numbers[j])),len(str(numbers[j+1])))+2
answers+=str((numbers[j]+numbers[j+1])).rjust(space_width)
answers+=' '
#print(answers)
j+=2
else:
space_width = max(len(str(numbers[j])),len(str(numbers[j+1])))+2
answers+=str((numbers[j]-numbers[j+1])).rjust(space_width)
answers+=' '
j+=2
#print(top_row)
#print(answers)
#formatting bottom line
for i in range(1,len(numbers),2):
space_width = max(len(str(numbers[i])),len(str(numbers[i-1])))+1
bottom_row += operations[i//2]
bottom_row += str(numbers[i]).rjust(space_width)
bottom_row += ' '
#print(bottom_row)
if show_answers:
arranged_problems = '\n'.join((top_row, bottom_row,dashes,answers))
else:
arranged_problems = '\n'.join((top_row, bottom_row,dashes))
return print(arranged_problems)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0
Challenge Information:
Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project