Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views1 page

Dsa 01 A

Uploaded by

nikita.khawase
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views1 page

Dsa 01 A

Uploaded by

nikita.khawase
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

class HashTable:

def __init__(self, size):


self.size = size
self.table = [[] for _ in range(size)] # Separate Chaining
self.table_lp = [None] * size # Linear Probing

def hash_function(self, key):


return key % self.size

def insert_separate_chaining(self, key, value):


hash_index = self.hash_function(key)
self.table[hash_index].append((key, value))

def search_separate_chaining(self, key):


hash_index = self.hash_function(key)
for i, (k, v) in enumerate(self.table[hash_index]):
if k == key:
return v, i + 1 # value, comparisons
return None, len(self.table[hash_index])

def insert_linear_probing(self, key, value):


hash_index = self.hash_function(key)
while self.table_lp[hash_index] is not None and self.table_lp[hash_index]
[0] != key:
hash_index = (hash_index + 1) % self.size
self.table_lp[hash_index] = (key, value)

def search_linear_probing(self, key):


hash_index = self.hash_function(key)
comparisons = 0
while self.table_lp[hash_index] is not None:
comparisons += 1
if self.table_lp[hash_index][0] == key:
return self.table_lp[hash_index][1], comparisons
hash_index = (hash_index + 1) % self.size
return None, comparisons

# Example usage
size = 10 # Size of the hash table
ht = HashTable(size)

# Assume telephone numbers as keys and client names as values


clients = [(123, 'Alice'), (234, 'Bob'), (345, 'Charlie'), (456, 'Dave'), (1234,
'Eve'), (2345, 'Frank')]

# Insert clients into hash table using both methods


for key, value in clients:
ht.insert_separate_chaining(key, value)
ht.insert_linear_probing(key, value)

# Search for a telephone number


key_to_find = 123
value_sc, comps_sc = ht.search_separate_chaining(key_to_find)
value_lp, comps_lp = ht.search_linear_probing(key_to_find)

print(f"Separate Chaining: Found {value_sc} with {comps_sc} comparisons")


print(f"Linear Probing: Found {value_lp} with {comps_lp} comparisons")

You might also like