From 3027b78e882dba0c360b4c1d2b73017131919049 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Doblas=20Jim=C3=A9nez?= Date: Fri, 6 Aug 2021 16:39:20 +0200 Subject: [PATCH] Module 12: Pattern Hash (Python code only) --- a.py | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/a.py b/a.py index 71941df..e783b7b 100644 --- a/a.py +++ b/a.py @@ -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")