Tell us what’s happening:
Hello! I’m currently working on the arithmetic formatting challenge on the PY4E course. When I run the calculations used by the test module code on IDLE my function seems to return all of the correct solutions, with the correct formatting, but there are still 2 tests which I always fail when I run main.py on repl.it. I’m guessing it’s due to some formatting issue but I’m not sure what to change. Thank you
Your code so far
def arithmetic_arranger(calcs, show_result=False):
calcarray = []
toprows = []
midrows = []
linerows = []
resultrows = []
if len(calcs) > 4:
return('Error: Too many problems.')
for basecalc in calcs:
parts = basecalc.split()
num1, op, num2 = parts[0], parts[1], parts[2]
if op not in '+-':
return("Error: Operator must be '+' or '-'.")
#print(num1+num2)
for c in num1+num2:
if c not in '1234567890':
return("Error: Numbers must only contain digits.")
parts = basecalc.split()
num1, op, num2 = parts[0], parts[1], parts[2]
result = str(eval(basecalc))
calcarray.append([num1, op, num2, result])
for splitcalc in calcarray:
length = max(len(splitcalc[0]), len(splitcalc[2]))+2
if length > 6:
return("Error: Numbers cannot be more than four digits.")
#toprow
space = ' '*(length-len(splitcalc[0]))
toprow = space + splitcalc[0]
#print(toprow)
toprows.append(toprow)
#midrow
space = ' '*(length-(1+len(splitcalc[2])))
midrow = op + space + splitcalc[2]
#print(midrow)
midrows.append(midrow)
#linerow
linerow = '-'*(length)
#print(linerow)
linerows.append(linerow)
#resultrow
result = splitcalc[3]
space = ' '*(length-len(splitcalc[3]))
resultrow = space + splitcalc[3]
#print(resultrow+'\n')
resultrows.append(resultrow)
line1 = toprows[0] + ' ' + toprows[1] + ' ' + toprows[2] + ' ' + toprows[3]
line2 = midrows[0] + ' ' + midrows[1] + ' ' + midrows[2] + ' ' + midrows[3]
line3 = linerows[0] + ' ' + linerows[1] + ' ' + linerows[2] + ' ' + linerows[3]
line4 = resultrows[0] + ' ' + resultrows[1] + ' ' + resultrows[2] + ' ' + resultrows[3]
finaloutput = line1+'\n'+line2+'\n'+line3
if show_result:
finaloutput += '\n'+line4
return(finaloutput)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36
.
Challenge: Arithmetic Formatter
Link to the challenge: