56 lines
2.0 KiB
Python
56 lines
2.0 KiB
Python
import re
|
|
|
|
|
|
def is_floatable(string: str) -> bool:
|
|
try:
|
|
float(string)
|
|
return True
|
|
except Exception:
|
|
return False
|
|
|
|
def arrange_individual(problem: str, solve: bool) -> bool:
|
|
parts = problem.split(' ')
|
|
solution = int(parts[0])
|
|
add = True
|
|
if solve:
|
|
for part in parts[1:]:
|
|
if part == '+':
|
|
add = True
|
|
elif part == '-':
|
|
add = False
|
|
elif add:
|
|
solution += int(part)
|
|
else:
|
|
solution -= int(part)
|
|
max_width = max([len(part) for part in parts]) + 1
|
|
arranged_problem = parts[0].rjust(max_width+1) + '\n'
|
|
for part in parts[1:]:
|
|
if is_floatable(part):
|
|
arranged_problem += part.rjust(max_width) + '\n'
|
|
else:
|
|
arranged_problem += part
|
|
arranged_problem += '-'*(max_width+1)
|
|
if solve:
|
|
arranged_problem += '\n'+str(solution).rjust(max_width+1)
|
|
return arranged_problem
|
|
|
|
def arithmetic_arranger(problems: list[str], solve: bool = False) -> str:
|
|
if (len(problems) > 5):
|
|
return "Error: Too many problems."
|
|
problems_str = ' '.join(problems)
|
|
if re.search(r"[/*]", problems_str):
|
|
return "Error: Operator must be '+' or '-'."
|
|
if re.search(r"[^0-9\+\-\s]", problems_str):
|
|
return "Error: Numbers must only contain digits."
|
|
problems_str_with_absolute_numbers = re.sub(r"\-([0-9])", r"\1", problems_str)
|
|
largest_digit_length = max(len(part) for part in problems_str_with_absolute_numbers.split(' '))
|
|
if (largest_digit_length > 4):
|
|
return "Error: Numbers cannot be more than four digits."
|
|
individually_arranged_problems = [arrange_individual(problem, solve) for problem in problems]
|
|
parts = [problem.split("\n") for problem in individually_arranged_problems]
|
|
arranged_problems = ""
|
|
for j in range(len(parts[0])):
|
|
for i in range(len(parts)):
|
|
arranged_problems += parts[i][j] + ' '*4
|
|
arranged_problems = arranged_problems.rstrip() + '\n'
|
|
return arranged_problems.rstrip('\n') |