Hi there. I wrote code that seems to have the desired output but some reason it does not pass the tests. It also says it doesn’t pass the check for giving an error message when letters are added instead of numbers, although it does actually do that when I run it.
I don’t understand what I’m doing wrong.
def arithmetic_arranger(problems, show_answers=False):
if len(problems) > 4:
return 'Error: Too many problems.'
toplist = []
bottomlist = []
dasheslist = []
answerslist = []
answer = 0
for problem in problems:
splitlist = problem.split() #break problems into their separate elements
if not splitlist[0].isnumeric() or not splitlist[2].isnumeric: #check only numbers were added
return 'Error: Numbers must only contain digits.'
if len(splitlist[0]) > len(splitlist[2]): #see which number is longer and set up the length
length = len(splitlist[0]) + 2
else:
length = len(splitlist[2]) + 2
if length > 6:
return 'Error: Numbers cannot be more than four digits.'
spaceslength = length - len(splitlist[0])
toplist.append(" " * spaceslength) #add proper number of spaces for top number to be right aligned
toplist.append(splitlist[0]) #add first number
toplist.append(" ") #add spaces to separate the problems
operator = splitlist[1]
if operator == "*" or operator == "/": #check for invalid functions
return "Error: Operator must be '+' or '-'."
elif operator == "+":
answer = int(splitlist[0]) + int(splitlist[2])
elif operator == "-":
answer = int(splitlist[0]) - int(splitlist[2])
answerslist.append((" " * (length - len(str(answer))))) #create the answers string, making it right aligned
answerslist.append(str(answer))
answerslist.append(" ")
bottomlist.append(operator)
bottomlist.append(" " * (length - len(str(splitlist[2])) - 1))
bottomlist.append(splitlist[2])
bottomlist.append(" ")
dasheslist.append("-"*length)
dasheslist.append(" ")
topliststring = "".join(toplist)
bottomliststring = "".join(bottomlist)
dashesliststring = "".join(dasheslist)
answersliststring = "".join(answerslist)
if show_answers==False:
problems = "\n".join([topliststring, bottomliststring, dashesliststring])
else:
problems = "\n".join([topliststring, bottomliststring, dashesliststring, answersliststring])
return problems
print(f'\n{arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"], True)}')```