Tell us what’s happening:
Basically I have been working on this code for hours to figure out what is going wrong, after checking i could not find any problems as my output is directly identical to the given solutions hence the problem
My Code
def arithmetic_arranger(problems, show_answers=False):
if len(problems) > 5:
return "Error: Too many problems."
lst1 = []
lst2 = []
lst3 = []
for i in range(len(problems)): #check if all numbers
sum = problems[i]
if "+" in sum:
opr = "+"
num1 = sum.split("+")[0].strip()
num2 = sum.split("+")[1].strip()
if not num1.isdigit() or not num2.isdigit():
return "Error: Numbers must only contain digits."
elif "-" in sum:
opr = "-"
num1 = sum.split("-")[0].strip()
num2 = sum.split("-")[1].strip()
if not num1.isdigit() or not num2.isdigit():
return "Error: Numbers must only contain digits."
for i in range(len(problems)): #check if length of numbers is 4 or less
sum = problems[i]
if "+" in sum:
opr = "+"
num1 = sum.split("+")[0].strip()
num2 = sum.split("+")[1].strip()
if len(num1) > 4 or len(num2) > 4:
return "Error: Numbers cannot be more than four digits."
elif "-" in sum:
opr = "-"
num1 = sum.split("-")[0].strip()
num2 = sum.split("-")[1].strip()
if len(num1) > 4 or len(num2) > 4:
return "Error: Numbers cannot be more than four digits."
for i in range(len(problems)): #check if opr is either + or -
sum = problems[i]
if "+" not in sum and "-" not in sum:
return "Error: Operator must be '+' or '-'."
for i in range(len(problems)):
sum = problems[i]
if "+" in sum:
opr = "+"
num1 = sum.split("+")[0].strip()
num2 = sum.split("+")[1].strip()
value = str(int(num1) + int(num2))
elif "-" in sum:
opr = "-"
num1 = sum.split("-")[0].strip()
num2 = sum.split("-")[1].strip()
value = str(int(num1) - int(num2))
width = max(len(num1), len(num2)) + 2 # Maximum width for alignment
lst1.append(num1.rjust(width))
lst2.append(opr + num2.rjust(width - 1))
lst3.append(value.rjust(width))
line1 = " ".join(lst1)
line2 = " ".join(lst2)
separator = ""
for i in range(len(lst2)):
dash = "-" * len(lst2[i])
separator += dash + " "
line3 = " ".join(lst3)
if show_answers:
arranged_problems = "\n".join((line1, line2, separator, line3))
else:
arranged_problems = "\n".join((line1, line2, separator))
print(arranged_problems)
return arranged_problems
#Example usage:
#problems = ["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]
#arithmetic_arranger(problems,True)
#arithmetic_arranger(["3801 - 2", "123 + 49"],True)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36
Challenge Information:
Scientific Computing with Python Projects - Arithmetic Formatter