From a2fa88f5611f878c6937abaab4f6858a203c37b6 Mon Sep 17 00:00:00 2001 From: William Carroll Date: Mon, 16 Nov 2020 17:13:39 +0000 Subject: [PATCH] Prefer mutative variant of delete for HashTable Instead of calling `filter(..)`. --- scratch/facebook/polynomial-rolling-hash.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/scratch/facebook/polynomial-rolling-hash.py b/scratch/facebook/polynomial-rolling-hash.py index ba288d631..0c7b7cb5a 100644 --- a/scratch/facebook/polynomial-rolling-hash.py +++ b/scratch/facebook/polynomial-rolling-hash.py @@ -5,9 +5,12 @@ def compute_hash(x): x[0] * P^0 + x[1] * P^1 + ... x[n-1] * P^(n-1) % M - P and M are constants. + P and M are constants where P represents the next available prime number + that's GTE the number of unique characters you'll be hashing. In the case of + all lowercase characters, of which there are 26, the next available prime + number is 31. """ - p = 31 # small prime number + p = 31 m = int(10e9) + 9 # large prime number power = 0 result = 0 @@ -18,6 +21,9 @@ def compute_hash(x): class HashTable(object): def __init__(self, size): + """ + Create a hash table with `size` buckets. + """ buckets = [] for _ in range(size): buckets.append([]) @@ -55,5 +61,12 @@ class HashTable(object): self.xs[h].append((key, val)) def delete(self, key): + """ + Remove entry `key` from the hash table. + """ h = self.compute_hash(key) - self.xs[h] = list(filter(lambda entry: entry[0] != key, self.xs[h])) + for i in range(len(self.xs[h])): + k, v = self.xs[h][i] + if k == key: + self.xs[h].remove((k, v)) + return