-
Notifications
You must be signed in to change notification settings - Fork 0
/
radex.py
55 lines (40 loc) · 1.21 KB
/
radex.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
from functools import reduce
class Node:
def __init__(self, value=''):
self.value = value
self.children = {}
class Tree:
def __init__(self):
self.root = Node()
def insert(self, word, node=None):
if len(word) < 1:
return None
if node is None:
node = self.root
c = word[0]
if c in node.children:
return self.insert(word[1:], node.children[c])
else:
node.children.update({c: Node(c)})
return self.insert(word[1:], node.children[c])
def regex(self, node=None):
if node is None:
node = self.root
if len(node.children) < 1:
return node.value
children = []
for c in node.children:
children.append(self.regex(node.children[c]))
if reduce((lambda x, y: x or y), ['[' in s for s in children]):
re = '|'.join(children)
re = '(' + re + ')'
else:
re = ''.join(children)
re = '[' + re + ']'
return node.value + re
f = open('./geohash-list.txt', 'r')
hashes = f.read().split(' ')
tree = Tree()
for hash in hashes:
tree.insert(hash)
print(tree.regex())