Hashing算法的Python索引为None

问题描述 投票:0回答:1

我将一些哈希算法的伪代码转换为python作为练习,它除了一个问题外它工作正常:当我搜索一个不存在的条目时,我得到TypeError: 'NoneType' object is not subscriptable

我完全理解为什么会出现这个错误,但我看不出一个避免它的好方法。有人可以告诉我如何修改代码,以便在这种情况下不会产生错误?

我可以使用try / except块但这看起来有点乱。我正在寻找最简单/最干净的方法。

我的代码如下。产生错误的行是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)) 
python hash nonetype
1个回答
3
投票

只需反转and运算符周围的表达式 - 在Python中,and短路,只要表达式为False,所以你应该首先检查None。此外,None检查可以简化一点(None是假的,没有必要明确检查is not None):

while hash_table[index] and hash_table[index][0] != search_key:
© www.soinside.com 2019 - 2024. All rights reserved.