I've been set a homework task by a tutor to create a procedure which hashes a string, or in a sense gives the index of the string in a hash table if it was hashed.
It was supposed to return 11, but returned 0, can someone help me figure out why?
def hash_string(keyword, buckets):
ords = []
for e in string_to_list(keyword):
ords.append(ord(e))
sum_of_ords = ords.pop()
for e in ords:
sum_of_ords = sum_of_ords * e
return sum_of_ords % buckets
print(hash_string('udacity', 12)) # should return 11 but returns 0?
Here is the string_to_list, I know theres probably a better way, but this is the only way I knew how without using google to search a built in method for this type of thing
def string_to_list(str):
result_list = []
i = 0
while i < len(str):
result_list.append(str[i:i + 1])
i += 1
return result_list
Here is how my tutor described the answer, but I don't undersand what he is doing with h? Is this just a simplified version of what I'm trying to do?
def hash_string(keyword, buckets):
h = 0
for c in keyword:
h = (h + ord(c)) % buckets
return h
listisn't necessary to iterate a string. Anyway, you can uselist(your_string)if you need to.