Tell us what’s happening:
Seems like only one code is accepted as correct. I am writing the code in Spyder/Visual Studio Code to cheach each case individually. After putting all togeteher, I can run each test case succesfully. However, while running it in the freeCodeCamp console I am getting errors in cases 5, 6, 7 and 8 for no reason. Any tip?
Your code so far
def arithmetic_arranger(problems, show_answers=False):
if len(problems) > 5: # Checks if problems are > 5.
raise ValueError('Error: Too many problems.')
else:
# List to store the different problems
first_line = []
second_line = []
dash_line = []
answer_line = []
# Loop to analyze each problem case.
for problem in problems:
element1 = ''
element2 = ''
operator = ''
# To obtain each operand and the operator.
elements = problem.split()
element1, operator, element2 = elements
#Checks if operator is not + or -.
if operator == '*':
raise ValueError("Operator must be '+' or '-'.")
elif operator == '/':
raise ValueError("Operator must be '+' or '-'.")
#Checks if operands are digits.
if not element1.isdigit() or not element2.isdigit():
raise ValueError('Error: Numbers must only contain digits.')
#Checks if operands are greater that 4 digits.
if len(element1) > 4 or len(element2) > 4:
raise ValueError('Error: Numbers cannot be more than four digits.')
#To determine the width.
width = max(len(element1), len(element2)) + 2
# Format each part of the equation.
first_line.append(element1.rjust(width))
second_line.append(operator + element2.rjust(width - 1))
dash_line.append('-' * width)
if show_answers:
if operator == '+':
result = int(element1) + int(element2)
elif operator == '-':
result = int(element1) - int(element2)
answer_line.append(str(result).rjust(width))
# Combine all parts into one formatted string
arranged_problems = (
" ".join(first_line) + "\n" +
" ".join(second_line) + "\n" +
" ".join(dash_line)
)
if show_answers:
arranged_problems += "\n" + " ".join(answer_line)
return arranged_problems
# Test the code
print(arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"],show_answers=True))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 OPR/114.0.0.0
Challenge Information:
Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project