检查我对哈希表的理解

时间:2012-11-25 23:35:37

标签: python hashtable implementation

我是第一年的计算机科学专业的学生。我正在尝试教自己哈希表进行面试。在阅读了一些关于它们的内容之后,我认为最好的方法是看看我是否得到它将是在Python中实现我自己的哈希表。这就是我所做的。请有人看看它,让我知道你的想法?我是否正确地理解了我的意思是使用哈希表做什么?

storage_array = []

def show_menu():
    menu_option = int(raw_input("Enter 1 to store data, Enter 2 to retrieve data: "))
    if (menu_option == 1):
        store_data()
    elif (menu_option == 2):
        retrieve_data()

def store_data():
    key_for_data = raw_input("Please enter the key for the data you want to store: ")
    actual_data = raw_input("Please enter the data you want to store: ")
    ascii_count = generate_hash(key_for_data)
    print ascii_count
    storage_array[ascii_count] = actual_data
    print "The data:'", actual_data, "'has been stored at index:'", ascii_count, "' which is the ascii count of:'", key_for_data, "'"
    show_menu()

def retrieve_data():
    key_for_data = raw_input("Enter the key for the data you want to retrieve: ")
    ascii_count = generate_hash(key_for_data)
    if (storage_array[ascii_count] == None):
        print "No data was stored under this key"
    else:
        print "The data you requested for key:'", key_for_data, "'with ASCII count:'", ascii_count, "' is:'", storage_array[ascii_count], "'"
    show_menu()

def generate_hash(input):
    character_list = list(input)
    ascii_count = 0
    for character_index in range(0,len(character_list)):
        ascii_count += ord(character_list[character_index])
    return ascii_count

def initiate_list():
    for repeat_index in range(0,1000):
        storage_array.append(None)
    print "List initiated with index's to 1000"

initiate_list()
show_menu()


##Or is it meant to hash the key like a dictionary and then store
##the value for that key in the hashed value in the hash table?

3 个答案:

答案 0 :(得分:2)

看起来你的一般概念是正确的。哈希表采用任意键,并通过一些特殊方法将其转换为数组的索引。

几点:

首先,最重要的是:如果密钥的ord()s之和大于1000,则generate_hash函数可以返回无效的索引。

要解决此问题,请让generate_hash返回ascii_count % 1000。如果您不知道%的含义,请阅读模数运算符(不要担心,它不会太复杂)。

第二次,也很重要:想想如果使用以下两个键会发生什么:abba。你正在做的事情并不一定是错的,但是当不同的键碰撞时理解哈希表的行为很重要。

第三,不太重要:你的for循环不必像在C / C ++中那样工作。你可以改变

for character_index in range(0,len(character_list)):
        ascii_count += ord(character_list[character_index])

for character in character_list:
        ascii_count += ord(character)

Python for循环非常奇特:)

总而言之,它看起来很棒!

答案 1 :(得分:0)

你有一个散列函数(我假设它为同一个输入产生相同的散列),你使用你的密钥上的散列函数产生的散列作为数组的索引来访问与密钥相关的数据,所以是的,看起来你有哈希表的要点。

要记住的一件好事是,您应该选择一个在输入上快速运行的散列函数,并且编写得足以合理地避免冲突(两个键产生相同散列的情况)。

答案 2 :(得分:0)

您的generate_hash()函数可以返回超出您表格的哈希值。

您还应该有一个处理碰撞的策略。最终会使用哈希表获得冲突。

您的generate_hash函数可以更简单地编写

def generate_hash(s):
    return sum(ord(c) for c in s)

如果使用模数1000,则可以避免哈希值落在表格外的问题

def generate_hash(s):
    return sum(ord(c) for c in s)%1000

retrieve_data()有一个错误。因为您没有考虑过碰撞,如果我使用密钥'ad'存储某些内容,我可以使用密钥'cb'检索它

相关问题