Search code examples
pythonhashnonetype

Python index into None for Hashing Algorithm


I've converting some pseudo-code for a hashing algorithm into python as an exercise and it works fine except for one problem: when I search for an entry which doesn't exist I get TypeError: 'NoneType' object is not subscriptable.

I fully understand why I get this error, but I can't see a good way to avoid it. Could someone please advise me how to modify the code so it doesn't produce an error in this situation?

I could use a try/except block but that seems a little messy. I'm looking for the simplest/cleanest approach.

My code is below. The line producing the error is while hash_table[index][0] != search_key and hash_table[index] is not None:

TABLE_SIZE = 10

customer_records = [  
    [45876, "Tom's data"],
    [32390, "Yolly's data"],
    [95312, "George's data"],
    [64636, "Bob's data"],
    [23467, "Susan's data"]]


def hash(key): # Anti-pattern to overwrite built in function
    return key % TABLE_SIZE


def insert(new_record, hash_table):
    index = hash(new_record[0])
    while hash_table[index] is not None:
        index += 1
        if index > TABLE_SIZE:
            index = 0
    hash_table[index] = new_record


def find_record(search_key, hash_table):
    index = hash(search_key)
    while hash_table[index][0] != search_key and hash_table[index] is not None:
        index += 1
        if index > TABLE_SIZE:
            index = 0
    if hash_table[index] is not None:
        return hash_table[index]


my_hash_table = [None] * TABLE_SIZE   

for record in customer_records:
    insert(record, my_hash_table)

print(find_record(45873, my_hash_table)) 

Solution

  • Just invert the expressions around the and operator - in Python, and short-circuits as soon as an expression is False, so you should always check for None first. Also, the None check can be simplified a bit (None is falsy, there's no need to explicitly check for is not None):

    while hash_table[index] and hash_table[index][0] != search_key: