Hey everyone,
I have been stuck trying to pass the Arithmetic Arranger project for the past little while. I am failing 2 tests out of the 6 and I cannot seem to figure out what is missing in my code. I copied the code into IDLE and the formatting looked fine for all the tests I did myself but there must be something that I am not seeing. Would someone be able to take a look at my code and give me some guidance in where I went wrong?
def arithmetic_arranger(problems, printOutput=False):
formattedStrings = ['', '', '', '']
if len(problems) < 5:
for i in range(len(problems)):
components = problems[i].split(' ')
if components[1] == '+' or components[1] == '-':
if components[0].isnumeric(
) == True and components[2].isnumeric() == True:
if len(components[0]) < 5 and len(components[2]) < 5:
#Create the formatted question strings
for i in range(4):
if (formattedStrings[i] == ''):
formattedStrings[i] += ''
else:
formattedStrings[i] += ' '
#In this part of the code, the equations are formatted with a right align and added to a list (to be printed later)
#If second number is shorter (or numbers both same length)
if (len(components[0]) >= len(components[2])):
formattedStrings[1] += components[1] + ' ' * (
len(components[0]) - len(components[2]) + 1)
formattedStrings[1] += components[2]
formattedStrings[0] += ' ' * 2 + components[0]
#If the first number is shorter
else:
formattedStrings[0] += ' ' * (
len(components[2]) - len(components[1]) + 2
) # Extra 2 spaces are to compensate for operator and space between digits
formattedStrings[0] += components[0]
formattedStrings[
1] += components[1] + ' ' + components[2]
#In this part of the code, the solution is created and added (if specified) and the other lines are finished
maxLength = max(len(components[0]), len(components[2]))
formattedStrings[2] += '-' * (maxLength + 2)
if (printOutput == True):
sol = ''
if (components[1] == '+'):
sol = str(
int(components[0]) + int(components[2]))
else:
sol = str(
int(components[0]) - int(components[2]))
formattedStrings[3] += ' ' * (
maxLength - len(sol) + 2)
formattedStrings[3] += sol
else:
return (
'Error: Numbers cannot be more than four digits.')
else:
return ('Error: Numbers must only contain digits.')
else:
return ("Error: Operator must be '+' or '-'.")
arrangedProblems = ''
for i in range(len(formattedStrings)):
if (i != len(formattedStrings) - 1):
arrangedProblems += formattedStrings[i] + '\n'
else:
arrangedProblems += formattedStrings[i]
return arrangedProblems
else:
return ("Error: Too many problems.")
Thanks
Michael