2014-10-10 35 views
1

我正在尝试使用一个字符串(键)并返回散列表的槽号的函数。 使得:(例如= 1,B = 2,C = 3,等等)使用字符串进行Python散列化

for key_word in ["John","Jane"]: 
    print(key_word, special_hash(key_word, 13)) 
>>> John 8 
    Jane 4 

该函数需要使用字母位置到字符串中的每个字母转换成数字形式。所以哈希值将为:John = 10 + 15 + 8 + 14 = 47 -----> = 47%tablesize(13)

+0

什么是'tablesize'? – thefourtheye 2014-10-10 05:28:14

+0

做“J”和“j”哈希是否一样? – mgilson 2014-10-10 05:28:19

+0

@thefourtheye - 我认为表格大小是13。 – mgilson 2014-10-10 05:28:59

回答

0

使用ord函数并减去ascii偏移量(一个字母为97代码,b 98,依此类推)

>>> ascii_offset = ord('a')-1 #http://www.asciitable.com/ 
>>> def special_hash(word, tablesize): 
...  return sum([ord(c) - ascii_offset for c in word.lower() ]) % tablesize 
... 
>>> special_hash('John',13) 
8 
>>> ##47%13 -> 8 
+0

谢谢。我有很多错误试图让结构正确,但工作。 – Newbie 2014-10-10 05:35:39

2

您可以将字符串以lower功能为小写,并通过在单词中的字符进行迭代,用for循环,这样

def special_hash(word, tablesize): 
    for char in word.lower(): 
     ... 

然后,可以得到与该字符对应的字符代码0功能。

def special_hash(word, tablesize): 
    total_value = 0 
    for char in word.lower(): 
     total_value += ord(char) - ord('a') + 1 

由于我们需要从字母中获取字符的偏移量,因此可以从当前值中减去第一个值。最后,您可以使用模运算%通过tablesize

def special_hash(word, tablesize): 
    total_value = 0 
    for char in word.lower(): 
     total_value += ord(char) - ord('a') + 1 
    return total_value % tablesize 

同样得到的余数可以用generator expression succintly书面和内置sum功能,这样

def special_hash(word, tablesize): 
    return sum(ord(char) - ord('a') + 1 for char in word.lower()) % tablesize 
+1

你当然为它工作+1:P – 2014-10-10 06:28:15

相关问题