Example #1

Command

./perfect_hash.py -v animals.txt

animals.txt

# this is a comment

Elephant,  4
Horse,    22
Camel,    10
Python,    1
dog,      12
Cat,      13

Execution Log

keys_file = 'animals.txt'
Reading table from file `animals.txt' to extract keys.
Reader options:
  comment: '#'
  splitby: ','
  keycol: 1
Number os keys: 6
tmpl_file = None
outname = 'std'

NG = 7

Generating graphs NG = 7 ...
Acyclic graph found after 3 trials.
NG = 7
OK
Format options:
  width: 76
  indent: 4
  delimiter: ', '
# =======================================================================
# ================= Python code for perfect hash function ===============
# =======================================================================

G = [0, 6, 0, 1, 5, 0, 3]

def hash_f(key, T):
    return sum(ord(T[i % 8]) * ord(c) for i, c in enumerate(key)) % 7

def perfect_hash(key):
    return (G[hash_f(key, "qjA8ZXGC")] +
            G[hash_f(key, "oSEriXp5")]) % 7

# ============================ Sanity check =============================

K = ["Elephant", "Horse", "Camel", "Python", "dog", "Cat"]
assert len(K) == 6

for h, k in enumerate(K):
    assert perfect_hash(k) == h

Test Program

#!/usr/bin/python3
# ===================================================================
# test animals hash table
# Elephant,  4
# Horse,    22
# Camel,    10
# Python,    1
# dog,      12
# Cat,      13
# ===================================================================

import user_interface as ui

# -------------------------------------------------------------------
#  Python code for perfect hash function 
# -------------------------------------------------------------------

G = [0, 6, 0, 1, 5, 0, 3]

def hash_f(key, T):
    return sum(ord(T[i % 8]) * ord(c) for i, c in enumerate(key)) % 7

def perfect_hash(key):
    return (G[hash_f(key, "qjA8ZXGC")] +
            G[hash_f(key, "oSEriXp5")]) % 7

K = ["Elephant", "Horse", "Camel", "Python", "dog", "Cat"]

X = [4, 22, 10, 1, 12, 13 ]    # return value associated with animals

# -------------------------------------------------------------------
# ---- main
# -------------------------------------------------------------------

if __name__ == '__main__':

    k_max = len(K) - 1         # length of K array

    while(True):

        print()
        print('Select: Elephant, Horse, Camel, Python, dog, Cat')
        print()
        s = ui.get_user_input('Enter animal name: ')
        if not s:
            break

        h = perfect_hash(s)

        print()
        print(f'Hash is {h}')

        if h > k_max or s != K[h]:
            print()
            print(f'{s} does not match')
            ui.pause()