Files
hello-algo/ja/codes/python/chapter_hashing/simple_hash.py
Yudong Jin d7b2277d2b Re-translate the Japanese version (#1871)
* Retranslate Japanese docs with GPT-5.4

* Retranslate Japanese code with GPT-5.4
2026-03-30 07:30:15 +08:00

59 lines
1.1 KiB
Python

"""
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:
"""XOR ハッシュ"""
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__":
key = "Hello アルゴリズム"
hash = add_hash(key)
print(f"加算ハッシュ値は {hash}")
hash = mul_hash(key)
print(f"乗算ハッシュ値は {hash}")
hash = xor_hash(key)
print(f"XOR ハッシュ値は {hash}")
hash = rot_hash(key)
print(f"回転ハッシュ値は {hash}")