Linear probing hash table python

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

class HashTable(object):
def __init__(self):
self.max_length = 8
self.max_load_factor = 0.75
self.length = 0
self.table = [None] * self.max_length
def __len__(self):
return self.length
def __setitem__(self, key, value):
self.length += 1
hashed_key = self._hash(key)
while self.table[hashed_key] is not None:
if self.table[hashed_key][0] == key:
self.length -= 1
hashed_key = self._increment_key(hashed_key)
tuple = (key, value)
self.table[hashed_key] = tuple
if self.length / float(self.max_length) >= self.max_load_factor:
def __getitem__(self, key):
index = self._find_item(key)
return self.table[index][1]
def __delitem__(self, key):
index = self._find_item(key)
self.table[index] = None
def _hash(self, key):
# TODO more robust
return hash(key) % self.max_length
def _increment_key(self, key):
return (key + 1) % self.max_length
def _find_item(self, key):
hashed_key = self._hash(key)
if self.table[hashed_key] is None:
raise KeyError
if self.table[hashed_key][0] != key:
original_key = hashed_key
while self.table[hashed_key][0] != key:
hashed_key = self._increment_key(hashed_key)
if self.table[hashed_key] is None:
raise KeyError
if hashed_key == original_key:
raise KeyError
return hashed_key
def _resize(self):
self.max_length *= 2
self.length = 0
old_table = self.table
self.table = [None] * self.max_length
for tuple in old_table:
if tuple is not None:
self[tuple[0]] = tuple[1]

What is linear probing in hash table?

Linear probing is a scheme in computer programming for resolving collisions in hash tables, data structures for maintaining a collection of key–value pairs and looking up the value associated with a given key. It was invented in 1954 by Gene Amdahl, Elaine M.

How do you create a hash table in Python?

Build a Hash Table in Python With TDD.
Take a Crash Course in Test-Driven Development..
Define a Custom HashTable Class..
Insert a Key-Value Pair..
Find a Value by Key..
Delete a Key-Value Pair..
Update the Value of an Existing Pair..
Get the Key-Value Pairs..
Use Defensive Copying..

What does __ hash __ do in Python?

The hash() method returns the hash value of an object if it has one. Hash values are just integers that are used to compare dictionary keys during a dictionary look quickly.

How do you handle collisions in a hash table in Python?

In open addressing, hash collisions are resolved by probing (explained below) . The hash table is just a contiguous block of memory (like an array, so you can do O(1) lookup by index). Each slot in the hash table can store one and only one entry. This is important.

Tải thêm tài liệu liên quan đến bài viết Linear probing hash table python