def check_input(problems):
if len(problems) < 5:
for p in problems:
if p.find('+') != -1 or p.find('-') != -1:
p_list = p.split(' ')
if p_list[0].isdigit() and p_list[2].isdigit():
if len(p_list[0]) < 5 and len(p_list[2]) < 5:
return True
else:
raise ValueError('Error: Numbers cannot be more than four digits.')
else:
raise ValueError("Error: Numbers must only contain digits.")
else:
raise ValueError("Error: Operator must be '+' or '-'.")
else:
raise ValueError('Error: Too many problems.')
def calculate_space(operand1, operand2):
operand1_len = len(operand1)
operand2_len = len(operand2)
len_deference = abs(operand1_len - operand2_len)
i = 0
space = ''
while i < len_deference:
space += ' '
i += 1
return space
def check_longest(op1, op2):
longest = 0
op1_length = len(op1)
op2_length = len(op2)
if op1_length > op2_length: longest = op1
elif op2_length > op1_length: longest = op2
else: longest = op1
return longest
def draw_line(op1, op2):
i = 0
line = '--'
longest = check_longest(op1, op2)
while i < len(longest):
line += '-'
i += 1
return line
def arithmetic_arranger(problems, show_answers=False):
if check_input(problems):
top = []
mid = []
bottom= []
for problem in problems:
problem_list = problem.split(' ')
operator = problem_list[1]
operand1 = problem_list[0]
operand2 = problem_list[2]
operand1_len = len(operand1)
operand2_len = len(operand2)
result = 0
space = calculate_space(operand1, operand2)
line = draw_line(operand1, operand2)
if operand1_len > operand2_len:
print(f" {operand1}\n{operator}{space} {operand2}\n{line} ")
elif operand2_len > operand1_len:
print(f" {space}{operand1}\n{operator} {operand2}\n{line} ")
else:
print(f" {operand1}\n{operator} {operand2}\n{line} ")
if show_answers:
if operator == '+':
result = int(operand1) + int(operand2)
elif operator == '-':
result = int(operand1) - int(operand2)
longest = check_longest(operand1, operand2)
answer_space = calculate_space(longest, str(result))
print(f' {answer_space}{result}')
return problems
print(f'\n{arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"], True)}')
Hello, so I can’t figure out to format the output correctly so that the problems are printed on the same line. I searched the forum for posts about the same issue and saw some people suggesting using a 2D array. I’m still unsure how to go about it or if it’s an optimal way to do it.
Please tell me if this is something I should figure out myself.
Sorry for the lack of comments, if they are needed to understand the code, please do tell.