gpt4 book ai didi

python - 检查我对哈希表的理解

转载 作者:行者123 更新时间:2023-12-01 05:52:55 27 4
gpt4 key购买 nike

我是计算机科学专业一年级的学生。我正在尝试自学哈希表以进行面试。在阅读了一些关于它们的文章后,我认为查看我是否得到它的最好方法是用 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?

最佳答案

看来您的总体概念是正确的。哈希表采用任意键,并通过某种特殊方法将其转换为数组的索引。

几点:

首先,也是最重要的:如果键的ord()总和大于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 循环非常奇特:)

总而言之,看起来很棒!

关于python - 检查我对哈希表的理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13556765/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com