Hashtable explanation

You can post your problem related to Computer Software Projects here. We will try our best to help you out.
Post Reply
Robert
Posts: 31
Joined: Sat Feb 18, 2017 7:21 am

Hashtable explanation

Post by Robert » Thu Mar 09, 2017 9:08 am

Code: Select all

class HashTable:
    def __init__(self):
        self.size = 11
        self.slots = [None] * self.size
        self.data = [None] * self.size

def put(self,key,data):
  hashvalue = self.hashfunction(key,len(self.slots))

  if self.slots[hashvalue] == None:
    self.slots[hashvalue] = key
    self.data[hashvalue] = data
  else:
    if self.slots[hashvalue] == key:
      self.data[hashvalue] = data  #replace
    else:
      nextslot = self.rehash(hashvalue,len(self.slots))
      while self.slots[nextslot] != None and \
                      self.slots[nextslot] != key:
        nextslot = self.rehash(nextslot,len(self.slots))

      if self.slots[nextslot] == None:
        self.slots[nextslot]=key
        self.data[nextslot]=data
      else:
        self.data[nextslot] = data #replace
I've been reading this bit of data structure on hashtable, and need explanation on this part below.

If key is already present, why is data being replaced?

Code: Select all

if self.slots[hashvalue] == key:
  self.data[hashvalue] = data  #replace
Also, can someone explain this part? Nextslot would be empty slot. And we just rehash and if it's not empty and key is not present, rehash again?

Code: Select all

nextslot = self.rehash(hashvalue,len(self.slots))
  while self.slots[nextslot] != None and \
                  self.slots[nextslot] != key:
    nextslot = self.rehash(nextslot,len(self.slots))

diksha92
Posts: 2
Joined: Fri Feb 22, 2019 5:35 am

Re: Hashtable explanation

Post by diksha92 » Mon Feb 25, 2019 4:45 am

Many Thanks for sharing such great information. As a digital marketer, I want such info.

Post Reply