1 year ago

#229461

test-img

xxmira

Hash table and hash function implementation

So this is an implementation for hash table https://www.programiz.com/dsa/hash-table that we took in class but I couldn't understand it. I have some question

  1. Is this like an array of size 10, like we have 10 bucket. we don't have built-in array in python so we do it with list right? this has nothing to do with 2 dimensional or something like that?
hashTable = [[],] * 10
  1. the if checks the number if it's even convert it to an odd number I get that, but don't get the while part why if the number is not prime we add 2 to it. does this grantee to get a prime number like if the number is odd and not prime we add 2 to it?
def getPrime(n):
    if n % 2 == 0:
        n = n + 1

    while not checkPrime(n):
        n += 2

    return n
  1. Can't get the logic behind this function at all,
  • why we send a fixed number like 10 to the getPrime function? where this number came from?

  • and doesn't that always give us the same return value?

  • what we mean by the return value is the capacity?

  • and why we divide the key by the capacity and get the remainder of it to be the index value of the hash table

def hashFunction(key):
    capacity = getPrime(10)
    return key % capacity

this is the code if it helps to look at it. any addition information about explaining about the code will be much appreciated.

# Python program to demonstrate working of HashTable 

hashTable = [[],] * 10

def checkPrime(n):
    if n == 1 or n == 0:
        return 0

    for i in range(2, n//2):
        if n % i == 0:
            return 0

    return 1


def getPrime(n):
    if n % 2 == 0:
        n = n + 1

    while not checkPrime(n):
        n += 2

    return n


def hashFunction(key):
    capacity = getPrime(10)
    return key % capacity


def insertData(key, data):
    index = hashFunction(key)
    hashTable[index] = [key, data]

def removeData(key):
    index = hashFunction(key)
    hashTable[index] = 0

insertData(123, "apple")
insertData(432, "mango")
insertData(213, "banana")
insertData(654, "guava")

print(hashTable)

removeData(123)

print(hashTable)

python

data-structures

hashtable

primes

hash-function

0 Answers

Your Answer

Accepted video resources