Tell us what’s happening:
My codes failed for the last two tests, it seems like for the last two test my code should have a special requirement the dashes should not be printed after the result is displayed, how can i get that done please.
the answer should be like that:arithmetic_arranger([“3 + 855”, “988 + 40”], True) should return 3 988\n+ 855 + 40\n----- -----\n 858 1028.
but mine is this: 3 988
- 855 + 40
858 1028
Your code so far
def arithmetic_arranger(problems, show_answers=False):
if len(problems) > 5:
return'Error: Too many problems.'
line1 = ""
line2 = ""
line3 = ""
line4 = ""
for problem in problems:
problem_item = problem.replace(" ", "")
if "+" in problem_item:
problem_item = problem_item.split("+")
operator = "+"
elif "-" in problem_item:
problem_item = problem_item.split("-")
operator = "-"
else:
return "Error: Operator must be '+' or '-'."
#check for non-digit operands
if not(problem_item[0].isdigit() and problem_item[1].isdigit()):
return 'Error: Numbers must only contain digits.'
if len(problem_item[0]) > 4 or len(problem_item[1]) > 4:
return 'Error: Numbers cannot be more than four digits.'
align = max([len(problem_item[0]), len(problem_item[1])]) + 2
if show_answers:
result = str(eval(problem_item[0] + operator + problem_item[1]))
line4 += result.rjust(align) + " "
line1 += problem_item[0].rjust(align) + " "
line2 += operator + problem_item[1].rjust(align - 1) + " "
line3 += "-"*(align) + " "
#remove trailling whitespace of each line
line1 = line1.rstrip()
line2 = line2.rstrip()
line3 = line3.rstrip()
final_string_format = "\n".join([line1, line2, line3])
if show_answers:
line4 = line4.rstrip()
final_string_format += "\n" + line4 + "\n" + line3
return final_string_format
print(arithmetic_arranger(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/126.0.0.0 Safari/537.36
Challenge Information:
Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project