-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharithmetic_arranger.py
60 lines (43 loc) · 1.75 KB
/
arithmetic_arranger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def arithmetic_arranger(problems, *args):
if len(problems) > 5:
return "Error: Too many problems."
arranged_problems = []
for index, value in enumerate(problems):
operation = value.split(" ")
if operation[1] not in "-+":
return "Error: Operator must be '+' or '-'."
if len(operation[0]) > 4 or len(operation[2]) > 4:
return "Error: Numbers cannot be more than four digits."
try:
value_1 = int(operation[0])
value_2 = int(operation[2])
except ValueError:
return "Error: Numbers must only contain digits."
# calculate the length of each line
longest_val = max(len(operation[0]), len(operation[2]))
width = longest_val + 2
L1 = f"{operation[0]:>{width}}"
L2 = operation[1] + f"{operation[2]:>{width-1}}"
d = '-' * width
try:
arranged_problems[0] += (' ' * 4) + L1
except IndexError:
arranged_problems.append(L1)
try:
arranged_problems[1] += (' ' * 4) + L2
except IndexError:
arranged_problems.append(L2)
try:
arranged_problems[2] += (' ' * 4) + d
except IndexError:
arranged_problems.append(d)
if args:
ans = int(operation[0]) + int(operation[2]) if operation[1] == '+' else int(operation[0]) - int(operation[2])
a = f"{str(ans):>{width}}"
try:
arranged_problems[3] += (' ' * 4) + a
except IndexError:
arranged_problems.append(a)
output = f"{arranged_problems[0]}\n{arranged_problems[1]}\n{arranged_problems[2]}"
output = output + f"\n{arranged_problems[3]}" if args else output
return output