Skip to content

Commit

Permalink
now with collision handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt committed Jul 9, 2018
1 parent e8b6641 commit c6e0d0c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
25 changes: 23 additions & 2 deletions python/app/hash_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,31 @@ def __init__(self, size=100):
self.values = self.size * [None]

def get(self, x):
return self.values[self.h(x)]
if not x:
raise ValueError('Invalid key')

i = self.h(x)
result = None

if self.values[i]:
pair = [p[1] for p in self.values[i] if p[0] == x]
if pair:
result = pair[0]

return result

def set(self, x, y):
self.values[self.h(x)] = y
"""Uses separate chaining for collsions
"""
if not x:
raise ValueError('Invalid key')

i = self.h(x)

if not self.values[i]:
self.values[i] = []

self.values[i].append([x, y])

def h(self, x):
return hash(x) % self.size
19 changes: 19 additions & 0 deletions python/tests/test_hash_table.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pytest
from app.hash_table import HashTable


Expand All @@ -6,3 +7,21 @@ def test_get_set():
ht.set('test', 1)
assert ht.get('test') == 1
assert ht.get('invalid') is None


def test_invalid_key():
ht = HashTable()
with pytest.raises(ValueError):
ht.set(None, 1)

with pytest.raises(ValueError):
ht.get(None)


def test_collisions():
ht = HashTable(1)
ht.set('test', 1)
ht.set('test2', 2)
assert ht.get('test') == 1
assert ht.get('test2') == 2
assert ht.get('test3') is None

0 comments on commit c6e0d0c

Please sign in to comment.