安全散列算法(secure hash algorithm,SHA)函数;给定一个字符串,SHA反回其散列值。
SHA可以用来判断两个文件是否相同。
SHA-0,SHA-1,SHA-2,SHA-3>
最安全的密码散列函数:bcrypt。
散列函数时间复杂度为O(1)。
散列函数将输入映射到数字;
散列函数总是将同样的输入映射到相同的索引。
散列函数将不同的输入映射到不同的索引。
散列函数知道数组有多大,只返回有效的索引。
散列表可由散列函数和数组创建,散列表是包含额外逻辑的数据结构。
数组和链表都被直接映射到内存,散列表使用散列函数来确定元素的存储位置。
散列表由键和值组成,将键映射到值。
Python提供了字典来实现散列表。
散列表可以实现DNS解析的功能。
散列表在检查是否重复方面速度非常快(dict的get方法)。
voted = {}
def check_voter(name):
if voted.get(name):
print("kick it out!")
else:
voted[name] = True
print("allow it to vote!")
if __name__ == '__main__':
check_voter("hello")
check_voter("hello")
散列表在缓存中的使用
缓存的工作原理:网站将数据记住不再重新计算。
缓存是一种常用的加速方式,大型网站都使用缓存,而缓存的数据则存储在散列表中。
缓存将URL映射到页面数据。
网站访问模型:
cache = {}
def get_page(url):
if cache.get(url):
return cache[url]
else:
data = get_data_from_server(url)
cache[url] = data
return data
if __name__ == '__main__':
get_page(xxx_url)