Arithmetic Formatter

Can someone please help be in solving this problem.

“Create a function that receives a list of strings that are arithmetic problems and returns the problems arranged vertically and side-by-side. The function should optionally take a second argument. When the second argument is set to True , the answers should be displayed”.

Sure I’ll help. Please show code you’ve come up with

What error message are you getting?

def arithmetic_arranger(problems, show_answers=False):
num_problems = len(problems)
if num_problems == 0:
return “”

max_length = max(len(problem) for problem in problems)
line1 = ""
line2 = ""
line3 = ""
line4 = ""

for problem in problems:
    if not problem.replace(" ", "").replace("+", "-").isdigit():
        return "Error: Input must contain only numbers and arithmetic operators."

    operator = "+" if "+" in problem else "-"
    operands = problem.split(operator)

    operand1 = operands[0].strip().rjust(max_length)
    operand2 = operands[1].strip().rjust(max_length)
    result = str(eval(problem)).rjust(max_length)

    line1 += operand1 + "    "
    line2 += operator + " " + operand2 + "    "
    line3 += "-" * (max_length + 2) + "    "
    if show_answers:
        line4 += result + "    "

arranged_problems = line1.rstrip() + "\n" + line2.rstrip() + "\n" + line3.rstrip()
if show_answers:
    arranged_problems += "\n" + line4.rstrip()

return arranged_problems

problems = [“32 + 698”, “3801 - 2”, “45 + 43”, “123 + 49”]
arranged = arithmetic_arranger(problems, show_answers=True)
print(arranged)

(deleted)

return arranged_problems

@giahseymehnbarseegia :+1:

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

as @johnsmith3321 indicates with his code here, you need to return arranged_problems not print

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.