-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharithmetic_arranger.py
More file actions
80 lines (65 loc) · 2.67 KB
/
Copy patharithmetic_arranger.py
File metadata and controls
80 lines (65 loc) · 2.67 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
################################################################################################
# File name: arithmetic_arranger.py
# Author: Johan Andrade
# Date created: 07 / 21 / 2021
# Date last modified 08 / 15 / 2021
# Description: Function receives a list of strings that are arithmetic problems and returns the
# problems arranged vertically and side-by-side.
# Refer to README.md for full description
################################################################################################
import re
def arithmetic_arranger(problems, solve=True):
first = ""
second = ""
lines = ""
sumexp = ""
string = ""
# max number of expressions allowed is 5
if (len(problems) > 5):
return "Error: Too many problems."
for problem in problems:
# check the input as valid digits and operators
if (re.search("[^\s0-9.+-]", problem)):
if (re.search("[/]", problem) or re.search("[*]", problem)):
return "Error: Operator must be '+' or '-'."
return "Error: Numbers must only contain digits."
# split problem into separate variables
firstNumber = problem.split(" ")[0]
operator = problem.split(" ")[1]
secondNumber = problem.split(" ")[2]
# check the length of the number has max 4 digits
if (len(firstNumber) >= 5 or len(secondNumber) >= 5):
return "Error: Numbers cannot be more than four digits."
# store the sum of the expression
sum = ""
if (operator == '+'):
sum = str(int(firstNumber) + int(secondNumber))
elif (operator == '-'):
sum = str(int(firstNumber) - int(secondNumber))
# set length of expression and right align the values
length = max(len(firstNumber), len(secondNumber)) + 2
top = str(firstNumber).rjust(length)
bottom = operator + str(secondNumber).rjust(length - 1)
# set length of the dashes/lines
line = ""
for s in range(length):
line += "-"
# right align the sum result
result = str(sum).rjust(length)
# add four spaces between each problem EXCEPT the last one (-1)
if problem != problems[-1]:
first += top + ' '
second += bottom + ' '
lines += line + ' '
sumexp += result + ' '
else:
first += top
second += bottom
lines += line
sumexp += result
# if solve is TRUE print the string with result sumexp
if solve:
string = first + '\n' + second + '\n' + lines + '\n' + sumexp
else:
string = first + '\n' + second + '\n' + lines
return string