Tell us what’s happening:
I can’t seem to gets this part working for some reason, and I can’t figure out where I have made a mistake:
Failed:6. arithmetic_arranger([“3 / 855”, “3801 - 2”, “45 + 43”, “123 + 49”]) should return “Error: Operator must be ‘+’ or ‘-’.”.
Your code so far
def arithmetic_arranger(problems, show_answers=False):
# Check if the number of problems exceeds 5
if len(problems) > 5:
return 'Error: Too many problems.'
# Initialize strings to build the vertical arrangement
top_line = ''
bottom_line = ''
dash_line = ''
answer_line = ''
for problem in problems:
# Split the problem into components (num1, operator, num2)
parts = problem.split()
# Ensure the problem has exactly three components: num1, operator, num2
if len(parts) != 3:
return 'Error: Invalid problem format.'
num1, operator, num2 = parts
# Check if the operator is valid
if operator not in ['+', '-']:
return 'Error: Operator must be "+" or "-".'
# Check if both operands are digits
if not num1.isdigit() or not num2.isdigit():
return 'Error: Numbers must only contain digits.'
# Check if the operands are no more than 4 digits
if len(num1) > 4 or len(num2) > 4:
return 'Error: Numbers cannot be more than four digits.'
# Calculate the result if show_answers is True
if show_answers:
if operator == '+':
result = str(int(num1) + int(num2))
elif operator == '-':
result = str(int(num1) - int(num2))
# Determine the max length for proper alignment
max_len = max(len(num1), len(num2)) + 2 # Add space for the operator
# Format each part of the problem for the current line
top_line += num1.rjust(max_len) + ' '
bottom_line += operator + ' ' + num2.rjust(max_len - 2) + ' '
dash_line += '-' * max_len + ' '
# Include the result if show_answers is True
if show_answers:
answer_line += result.rjust(max_len) + ' '
# Strip trailing spaces from each line
top_line = top_line.rstrip()
bottom_line = bottom_line.rstrip()
dash_line = dash_line.rstrip()
if show_answers:
answer_line = answer_line.rstrip()
# Combine all parts into the final output
if show_answers:
return f"{top_line}\n{bottom_line}\n{dash_line}\n{answer_line}"
else:
return f"{top_line}\n{bottom_line}\n{dash_line}"
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 Edg/131.0.0.0
Challenge Information:
Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project