forked from cs50/help50-deprecated
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.py
48 lines (41 loc) · 1.48 KB
/
tools.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
import re
import string
# extracts a single character above the ^
def char_extract(lines):
if len(lines) < 2 or not re.search(r"\^", lines[1]):
return
index = lines[1].index("^")
if len(lines[0]) < index + 1:
return
return lines[0][lines[1].index("^")]
# extracts all characters above the first sequence of ~
def tilde_extract(lines):
if len(lines) < 2 or not re.search(r"~", lines[1]):
return
start = lines[1].index("~")
length = 1
while len(lines[1]) > start + length and lines[1][start + length] == "~":
length += 1
if len(lines[0]) < start + length:
return
return lines[0][start:start+length]
# extract the name of a variable above the ^
# by default, assumes that ^ is under the first character of the variable
# if left_aligned is set to False, ^ is under the next character after the variable
def var_extract(lines, left_aligned=True):
if len(lines) < 2 or not re.search(r"\^", lines[1]):
return
permissibles = string.ascii_letters + string.digits + '_'
index = lines[1].index("^")
var = ""
if left_aligned:
while len(lines[0]) > index + 1 and lines[0][index] in permissibles:
var += lines[0][index]
index += 1
elif len(lines[0]) > index + 1:
index -= 1
while index >= 0 and lines[0][index] in permissibles:
var = lines[0][index] + var
index -= 1
if len(var) > 0:
return var