Module 9: Search the Library (Python code only)

This commit is contained in:
David Doblas Jiménez 2021-07-20 14:38:48 +02:00
parent e39354cb15
commit 6df8d25296
1 changed files with 48 additions and 5 deletions

53
a.py
View File

@ -1,9 +1,41 @@
def ToUpper(s):
return s.upper()
class Words:
def __init__(self):
self.word = []
num_buckets = 1001
def bucket(s):
assert(len(s) != 0)
i = 0
for c in s:
i = (i * 217) + ord(c)
i = abs(i)
b = i % num_buckets
assert(b >= 0 and b < num_buckets)
return b
class Library:
def __init__(self):
# master vector of word
self.words = []
self.words = Words()
self.counts = {}
self.shelves = {}
for i in range(num_buckets):
self.shelves[i] = []
def IsWord(self, s):
for Words.word in self.shelves[bucket(s)]:
if s == Words.word:
return True
return False
def ComputeStats(self):
# assert self.counts == {}
@ -28,8 +60,14 @@ class Library:
def ReadFromFile(self, filename):
with open(filename, 'r') as f:
for line in f:
self.words.append(line)
print(f"Read {len(self.words)} words from file '{filename}'")
line = ToUpper(line.rstrip())
self.words.word.append(line)
self.shelves[bucket(line)].append(line)
print(f"Read {len(self.words.word)} words from file '{filename}'")
def DebugBuckets(self):
for i in range(len(self.shelves)):
print(f"[{i}] {len(self.shelves[i])}")
class Grid:
@ -68,8 +106,13 @@ class Grid:
if __name__ == "__main__":
lib = Library()
lib.ReadFromFile("top_12000.txt")
lib.ComputeStats()
lib.PrintStats()
# lib.ComputeStats()
# lib.PrintStats()
print(lib.IsWord("DOG"))
print(lib.IsWord("CAT"))
print(lib.IsWord("THANKS"))
lib.DebugBuckets()
# grid = Grid("MY GRID")
# grid.LoadFromFile("test")