您可以将字符串以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
什么是'tablesize'? – thefourtheye 2014-10-10 05:28:14
做“J”和“j”哈希是否一样? – mgilson 2014-10-10 05:28:19
@thefourtheye - 我认为表格大小是13。 – mgilson 2014-10-10 05:28:59