-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParseList.py
50 lines (49 loc) · 1.2 KB
/
ParseList.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
def parseList(expression):
if expression[0] == '(' and expression[-1] == ')' or expression[0] == '[' and expression[-1] == ']':
expression = expression[1:-1]
if not expression:
return []
stack = []
curr_list = []
curr_element = ""
for c in expression:
if c == "[":
if curr_element:
curr_list.append(get_element(curr_element))
curr_element = ""
stack.append(curr_list)
curr_list = []
elif c == "]":
if curr_element:
curr_list.append(get_element(curr_element))
curr_element = ""
if not stack:
raise ValueError("Mismatched brackets1")
last_list = stack.pop()
last_list.append(curr_list)
curr_list = last_list
elif c == ",":
if curr_element:
curr_list.append(get_element(curr_element))
curr_element = ""
else:
curr_element += c
if curr_element:
curr_list.append(get_element(curr_element))
if stack:
raise ValueError("Mismatched brackets2")
return curr_list
def get_element(element):
try:
return int(element)
except ValueError:
pass
try:
return float(element)
except ValueError:
pass
if element[0] == '"' and element[-1] == '"':
return element[1:-1]
if element[0] == "'" and element[-1] == "'":
return element[1:-1]
return element