Add the section of hash algorithm. Refactor the section of hash map. (#555)
parent
4dddbd1e67
commit
29e6617ec1
@ -0,0 +1,36 @@
|
||||
"""
|
||||
File: built_in_hash.py
|
||||
Created Time: 2023-06-15
|
||||
Author: Krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys, os.path as osp
|
||||
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from modules import *
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
num = 3
|
||||
hash_num = hash(num)
|
||||
print(f"整数 {num} 的哈希值为 {hash_num}")
|
||||
|
||||
bol = True
|
||||
hash_bol = hash(bol)
|
||||
print(f"布尔量 {bol} 的哈希值为 {hash_bol}")
|
||||
|
||||
dec = 3.14159
|
||||
hash_dec = hash(dec)
|
||||
print(f"小数 {dec} 的哈希值为 {hash_dec}")
|
||||
|
||||
str = "Hello 算法"
|
||||
hash_str = hash(str)
|
||||
print(f"字符串 {str} 的哈希值为 {hash_str}")
|
||||
|
||||
tup = (12836, "小哈")
|
||||
hash_tup = hash(tup)
|
||||
print(f"元组 {tup} 的哈希值为 {hash(hash_tup)}")
|
||||
|
||||
obj = ListNode(0)
|
||||
hash_obj = hash(obj)
|
||||
print(f"节点对象 {obj} 的哈希值为 {hash_obj}")
|
@ -0,0 +1,56 @@
|
||||
"""
|
||||
File: simple_hash.py
|
||||
Created Time: 2023-06-15
|
||||
Author: Krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def add_hash(key: str) -> int:
|
||||
"""加法哈希"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash += ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
def mul_hash(key: str) -> int:
|
||||
"""乘法哈希"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash = 31 * hash + ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
def xor_hash(key: str) -> int:
|
||||
"""异或哈希"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash ^= ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
def rot_hash(key: str) -> int:
|
||||
"""旋转哈希"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash = (hash << 4) ^ (hash >> 28) ^ ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
hash = add_hash("Hello 算法")
|
||||
print(f"加法哈希值为 {hash}")
|
||||
|
||||
hash = mul_hash("Hello 算法")
|
||||
print(f"乘法哈希值为 {hash}")
|
||||
|
||||
hash = xor_hash("Hello 算法")
|
||||
print(f"异或哈希值为 {hash}")
|
||||
|
||||
hash = rot_hash("Hello 算法")
|
||||
print(f"旋转哈希值为 {hash}")
|
After Width: | Height: | Size: 82 KiB |
After Width: | Height: | Size: 82 KiB |
Loading…
Reference in new issue