Tell us what’s happening:
Can someone Help me? I’m stuck on this problem. Visually, all the code passes, and I’ve checked all of the problems:
- numbers are right aligned
- problems separated with 4 spaces
- dashes at the bottom
- operand is always separated with 1 white space from largest operator
The special if clauses pass but for some reason the rest doesn’t, aka, code fails at (1,2,3,4,9,10). In spite of that, the results are the same…
Your code so far
def arithmetic_arranger(problems, show_answers=False):
#1 check length
if len(problems) > 5:
return "Error: Too many problems."
#2 check operand
for n in problems:
space = n.replace(" ", "")
if "+" in space:
sign = "+"
elif "-" in space:
sign = "-"
else:
sign = None
if sign not in ["+", "-"]:
return "Error: Operator must be '+' or '-'."
#3 check non-digits
remove_sign = n.replace("+","").replace("-","").replace(" ","")
if remove_sign.isnumeric() == False:
return "Error: Numbers must only contain digits."
#4 check operand length
split_val = n.split(" ")
val1 = split_val[0]
val2 = split_val[2]
if len(val1) > 4 or len(val2) > 4:
return "Error: Numbers cannot be more than four digits."
#5 create arithmetic_arranger
resultsval1 = []
resultsval2 = []
results = []
dashes = []
for n in problems:
split_val = n.split(" ")
val1 = int(split_val[0])
val2 = int(split_val[2])
operand = split_val[1]
if operand == "+":
result = val1 + val2
else:
result = val1 - val2
max_len = len(str(max(val1, val2, result))) + 2
space_remain_val1 = max_len - len(str(val1))
space_remain_val2 = (max_len - len(str(val2))) - 1
space_remain_result = max_len - len(str(result))
number_of_dashes = max_len
resultsval1.append(f"{' ' * space_remain_val1}{val1}")
resultsval2.append(f"{operand}{' ' * space_remain_val2}{val2}")
results.append(f"{' ' * space_remain_result}{result}")
dashes.append(f"{'-' * number_of_dashes}")
if show_answers == True:
print(f"{' '.join(resultsval1)}\n{' '.join(resultsval2)}\n{' '.join(dashes)}\n{' '.join(results)}")
else:
print(f"{' '.join(resultsval1)}\n{' '.join(resultsval2)}\n{' '.join(dashes)}")
return problems
arithmetic_arranger(["3 + 855", "988 + 40"],True)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36
Challenge Information:
Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project