ctci/07. Object-Oriented design/7.12. Hash table.md

44 lines
844 B
Markdown

# 7.12. Hash table
> Design and implement a hash table which uses chaining (linked lists) to handle collissions
## Non-OOP solution
```python
hash_num = 10
def hash_table(vals):
items = [] * hash_num
for v in vals:
mod = v % hash_num
if items[mod]:
items[mod].append(v)
continue
items[mod] = [v]
return items
```
## OOP solution
```python
class hashTable:
def __init__(self, hash_num=10):
self.items = []
self.hash_num = hash_num
def create_hashtable(self, vals):
items = [[] * hash_num]
for v in vals:
items[v % hash_num].append(v)
return items
def main():
vals = [1,3,4,5,10,11,13,14]
hasht = hashTable()
items = hasht.create_hashtable(vals)
print(items)
if __name__ == "__main__":
main()
```