I’m doing the Build an arithmetic formatter project and my code (even though I know it can surely be done in a simpler way) is not working with what it asks me to do, despite the output being correct.
def arithmetic_arranger(problems, show_answers=False):
if len(problems) > 5:
return "Error: Too many problems."
for prob in problems:
if prob.find("+") == -1 and prob.find("-") == -1:
return "Error: Operator must be '+' or '-'."
split_prob = prob.split(" ")
if not split_prob[0].isnumeric() or not split_prob[2].isnumeric():
return "Error: Numbers must only contain digits."
if len(split_prob[0]) > 4 or len(split_prob[2]) > 4:
return "Error: Numbers cannot be more than four digits."
results = []
no_results = []
for prob in problems:
split_prob = prob.split(" ")
longest_operand = 0
longest_operand = max(len(split_prob[0]), len(split_prob[2]))
if split_prob[1] == '+':
result = int(split_prob[0]) + int(split_prob[2])
else:
result = int(split_prob[0]) - int(split_prob[2])
block_with_result = f"{split_prob[0].rjust(longest_operand+2)}\n{split_prob[1]}{split_prob[2].rjust(longest_operand+1)}\n{'-'*((longest_operand)+2)}\n{str(result).rjust(longest_operand+2)}"
results.append(block_with_result)
block_without_result = f"{split_prob[0].rjust(longest_operand+2)}\n{split_prob[1]}{split_prob[2].rjust(longest_operand+1)}\n{'-'*((longest_operand)+2)}"
no_results.append(block_without_result)
lines = ["", "", "", ""]
if show_answers:
for block in results:
split_block = block.split("\n")
ran = len(split_block)
for i in range(ran):
lines[i] += split_block[i] + " "
final_output = "\n".join(lines)
return final_output
else:
for block in no_results:
split_block = block.split("\n")
ran = len(split_block)
for i in range(ran):
lines[i] += split_block[i] + " "
final_output = "\n".join(lines)
return final_output
# print(f'\n{arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49", "112 * 5"])}')
print(arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49", "888 + 40"]))
print(arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49", "888 + 40", "653 + 87"]))
print(arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49", "888 + 40", "653 + 87"]))
print(arithmetic_arranger(["98 + 3g5", "3801 - 2", "45 + 43", "123 + 49"]))
print(arithmetic_arranger(["11 + 4", "3801 - 2999", "1 + 2", "123 + 49", "1 - 9380"]))
print(arithmetic_arranger(["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]))
print(arithmetic_arranger(["1 + 2", "1 - 9380"]))
print(arithmetic_arranger(["3 + 855", "988 + 40"], True))
print(arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49", "988 + 40"], True))