Module 12: Pattern Hash (Python code only)

This commit is contained in:
David Doblas Jiménez 2021-08-06 16:39:20 +02:00
parent b27c93dfd2
commit 3027b78e88
1 changed files with 25 additions and 8 deletions

33
a.py
View File

@ -2,11 +2,16 @@ def ToUpper(s):
return s.upper()
## ----------------------------------------------------------------------------
##-Words
class Words:
def __init__(self):
self.word = []
## ----------------------------------------------------------------------------
##-Library
class Library:
def __init__(self):
@ -16,6 +21,10 @@ class Library:
# hash table
self.word_map_ = {}
# Returns NULL if can't find any matches to the given pattern
def FindWord(self, s):
print(list(key for key, values in self.word_map_.items() if s in values))
def IsWord(self, s):
return s in self.word_map_
@ -39,12 +48,26 @@ class Library:
assert (i >= 0 and i < len(self.words_))
return self.words_[i]
def CreatePatternHash(self, w):
len_w = len(w)
num_patterns = 1 << len_w
# print(f"PATTERN HASH on {w}")
self.word_map_[w] = []
for i in range(num_patterns):
# print(f" {i}")
tmp = list(w)
for j in range(len_w):
if ((i >> j) & 1):
tmp[j] = "-"
# print(f' {"".join(tmp)}')
self.word_map_[w].append("".join(tmp))
def ReadFromFile(self, filename):
with open(filename, 'r') as f:
for line in f:
line = ToUpper(line.rstrip())
self.words_.word.append(line)
self.word_map_[line] = line
self.CreatePatternHash(line)
print(f"Read {len(self.words_.word)} words from file '{filename}'")
def DebugBuckets(self):
@ -88,14 +111,8 @@ class Grid:
if __name__ == "__main__":
lib = Library()
lib.ReadFromFile("top_12000.txt")
# lib.ComputeStats()
# lib.PrintStats()
print(lib.IsWord("DOG"))
print(lib.IsWord("CAT"))
print(lib.IsWord("THANKS"))
print(lib.IsWord("TFAFAS"))
lib.DebugBuckets()
lib.FindWord("D--")
# grid = Grid("MY GRID")
# grid.LoadFromFile("test")