mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 12:58:42 +08:00
translation: Add Python and Java code for EN version (#1345)
* Add the intial translation of code of all the languages * test * revert * Remove * Add Python and Java code for EN version
This commit is contained in:
117
en/codes/python/chapter_hashing/array_hash_map.py
Normal file
117
en/codes/python/chapter_hashing/array_hash_map.py
Normal file
@ -0,0 +1,117 @@
|
||||
"""
|
||||
File: array_hash_map.py
|
||||
Created Time: 2022-12-14
|
||||
Author: msk397 (machangxinq@gmail.com)
|
||||
"""
|
||||
|
||||
|
||||
class Pair:
|
||||
"""Key-value pair"""
|
||||
|
||||
def __init__(self, key: int, val: str):
|
||||
self.key = key
|
||||
self.val = val
|
||||
|
||||
|
||||
class ArrayHashMap:
|
||||
"""Hash table based on array implementation"""
|
||||
|
||||
def __init__(self):
|
||||
"""Constructor"""
|
||||
# Initialize an array, containing 100 buckets
|
||||
self.buckets: list[Pair | None] = [None] * 100
|
||||
|
||||
def hash_func(self, key: int) -> int:
|
||||
"""Hash function"""
|
||||
index = key % 100
|
||||
return index
|
||||
|
||||
def get(self, key: int) -> str:
|
||||
"""Query operation"""
|
||||
index: int = self.hash_func(key)
|
||||
pair: Pair = self.buckets[index]
|
||||
if pair is None:
|
||||
return None
|
||||
return pair.val
|
||||
|
||||
def put(self, key: int, val: str):
|
||||
"""Add operation"""
|
||||
pair = Pair(key, val)
|
||||
index: int = self.hash_func(key)
|
||||
self.buckets[index] = pair
|
||||
|
||||
def remove(self, key: int):
|
||||
"""Remove operation"""
|
||||
index: int = self.hash_func(key)
|
||||
# Set to None, representing removal
|
||||
self.buckets[index] = None
|
||||
|
||||
def entry_set(self) -> list[Pair]:
|
||||
"""Get all key-value pairs"""
|
||||
result: list[Pair] = []
|
||||
for pair in self.buckets:
|
||||
if pair is not None:
|
||||
result.append(pair)
|
||||
return result
|
||||
|
||||
def key_set(self) -> list[int]:
|
||||
"""Get all keys"""
|
||||
result = []
|
||||
for pair in self.buckets:
|
||||
if pair is not None:
|
||||
result.append(pair.key)
|
||||
return result
|
||||
|
||||
def value_set(self) -> list[str]:
|
||||
"""Get all values"""
|
||||
result = []
|
||||
for pair in self.buckets:
|
||||
if pair is not None:
|
||||
result.append(pair.val)
|
||||
return result
|
||||
|
||||
def print(self):
|
||||
"""Print hash table"""
|
||||
for pair in self.buckets:
|
||||
if pair is not None:
|
||||
print(pair.key, "->", pair.val)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize hash table
|
||||
hmap = ArrayHashMap()
|
||||
|
||||
# Add operation
|
||||
# Add key-value pair (key, value) to the hash table
|
||||
hmap.put(12836, "Ha")
|
||||
hmap.put(15937, "Luo")
|
||||
hmap.put(16750, "Suan")
|
||||
hmap.put(13276, "Fa")
|
||||
hmap.put(10583, "Ya")
|
||||
print("\nAfter adding, the hash table is\nKey -> Value")
|
||||
hmap.print()
|
||||
|
||||
# Query operation
|
||||
# Enter key to the hash table, get value
|
||||
name = hmap.get(15937)
|
||||
print("\nEnter student ID 15937, found name " + name)
|
||||
|
||||
# Remove operation
|
||||
# Remove key-value pair (key, value) from the hash table
|
||||
hmap.remove(10583)
|
||||
print("\nAfter removing 10583, the hash table is\nKey -> Value")
|
||||
hmap.print()
|
||||
|
||||
# Traverse hash table
|
||||
print("\nTraverse key-value pairs Key->Value")
|
||||
for pair in hmap.entry_set():
|
||||
print(pair.key, "->", pair.val)
|
||||
|
||||
print("\nIndividually traverse keys Key")
|
||||
for key in hmap.key_set():
|
||||
print(key)
|
||||
|
||||
print("\nIndividually traverse values Value")
|
||||
for val in hmap.value_set():
|
||||
print(val)
|
||||
37
en/codes/python/chapter_hashing/built_in_hash.py
Normal file
37
en/codes/python/chapter_hashing/built_in_hash.py
Normal file
@ -0,0 +1,37 @@
|
||||
"""
|
||||
File: built_in_hash.py
|
||||
Created Time: 2023-06-15
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import ListNode
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
num = 3
|
||||
hash_num = hash(num)
|
||||
print(f"Integer {num}'s hash value is {hash_num}")
|
||||
|
||||
bol = True
|
||||
hash_bol = hash(bol)
|
||||
print(f"Boolean {bol}'s hash value is {hash_bol}")
|
||||
|
||||
dec = 3.14159
|
||||
hash_dec = hash(dec)
|
||||
print(f"Decimal {dec}'s hash value is {hash_dec}")
|
||||
|
||||
str = "Hello algorithm"
|
||||
hash_str = hash(str)
|
||||
print(f"String {str}'s hash value is {hash_str}")
|
||||
|
||||
tup = (12836, "Ha")
|
||||
hash_tup = hash(tup)
|
||||
print(f"Tuple {tup}'s hash value is {hash(hash_tup)}")
|
||||
|
||||
obj = ListNode(0)
|
||||
hash_obj = hash(obj)
|
||||
print(f"Node object {obj}'s hash value is {hash_obj}")
|
||||
50
en/codes/python/chapter_hashing/hash_map.py
Normal file
50
en/codes/python/chapter_hashing/hash_map.py
Normal file
@ -0,0 +1,50 @@
|
||||
"""
|
||||
File: hash_map.py
|
||||
Created Time: 2022-12-14
|
||||
Author: msk397 (machangxinq@gmail.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import print_dict
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize hash table
|
||||
hmap = dict[int, str]()
|
||||
|
||||
# Add operation
|
||||
# Add key-value pair (key, value) to the hash table
|
||||
hmap[12836] = "Ha"
|
||||
hmap[15937] = "Luo"
|
||||
hmap[16750] = "Suan"
|
||||
hmap[13276] = "Fa"
|
||||
hmap[10583] = "Ya"
|
||||
print("\nAfter adding, the hash table is\nKey -> Value")
|
||||
print_dict(hmap)
|
||||
|
||||
# Query operation
|
||||
# Enter key to the hash table, get value
|
||||
name: str = hmap[15937]
|
||||
print("\nEnter student ID 15937, found name " + name)
|
||||
|
||||
# Remove operation
|
||||
# Remove key-value pair (key, value) from the hash table
|
||||
hmap.pop(10583)
|
||||
print("\nAfter removing 10583, the hash table is\nKey -> Value")
|
||||
print_dict(hmap)
|
||||
|
||||
# Traverse hash table
|
||||
print("\nTraverse key-value pairs Key->Value")
|
||||
for key, value in hmap.items():
|
||||
print(key, "->", value)
|
||||
|
||||
print("\nIndividually traverse keys Key")
|
||||
for key in hmap.keys():
|
||||
print(key)
|
||||
|
||||
print("\nIndividually traverse values Value")
|
||||
for val in hmap.values():
|
||||
print(val)
|
||||
118
en/codes/python/chapter_hashing/hash_map_chaining.py
Normal file
118
en/codes/python/chapter_hashing/hash_map_chaining.py
Normal file
@ -0,0 +1,118 @@
|
||||
"""
|
||||
File: hash_map_chaining.py
|
||||
Created Time: 2023-06-13
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from chapter_hashing.array_hash_map import Pair
|
||||
|
||||
|
||||
class HashMapChaining:
|
||||
"""Chained address hash table"""
|
||||
|
||||
def __init__(self):
|
||||
"""Constructor"""
|
||||
self.size = 0 # Number of key-value pairs
|
||||
self.capacity = 4 # Hash table capacity
|
||||
self.load_thres = 2.0 / 3.0 # Load factor threshold for triggering expansion
|
||||
self.extend_ratio = 2 # Expansion multiplier
|
||||
self.buckets = [[] for _ in range(self.capacity)] # Bucket array
|
||||
|
||||
def hash_func(self, key: int) -> int:
|
||||
"""Hash function"""
|
||||
return key % self.capacity
|
||||
|
||||
def load_factor(self) -> float:
|
||||
"""Load factor"""
|
||||
return self.size / self.capacity
|
||||
|
||||
def get(self, key: int) -> str | None:
|
||||
"""Query operation"""
|
||||
index = self.hash_func(key)
|
||||
bucket = self.buckets[index]
|
||||
# Traverse the bucket, if the key is found, return the corresponding val
|
||||
for pair in bucket:
|
||||
if pair.key == key:
|
||||
return pair.val
|
||||
# If the key is not found, return None
|
||||
return None
|
||||
|
||||
def put(self, key: int, val: str):
|
||||
"""Add operation"""
|
||||
# When the load factor exceeds the threshold, perform expansion
|
||||
if self.load_factor() > self.load_thres:
|
||||
self.extend()
|
||||
index = self.hash_func(key)
|
||||
bucket = self.buckets[index]
|
||||
# Traverse the bucket, if the specified key is encountered, update the corresponding val and return
|
||||
for pair in bucket:
|
||||
if pair.key == key:
|
||||
pair.val = val
|
||||
return
|
||||
# If the key is not found, add the key-value pair to the end
|
||||
pair = Pair(key, val)
|
||||
bucket.append(pair)
|
||||
self.size += 1
|
||||
|
||||
def remove(self, key: int):
|
||||
"""Remove operation"""
|
||||
index = self.hash_func(key)
|
||||
bucket = self.buckets[index]
|
||||
# Traverse the bucket, remove the key-value pair from it
|
||||
for pair in bucket:
|
||||
if pair.key == key:
|
||||
bucket.remove(pair)
|
||||
self.size -= 1
|
||||
break
|
||||
|
||||
def extend(self):
|
||||
"""Extend hash table"""
|
||||
# Temporarily store the original hash table
|
||||
buckets = self.buckets
|
||||
# Initialize the extended new hash table
|
||||
self.capacity *= self.extend_ratio
|
||||
self.buckets = [[] for _ in range(self.capacity)]
|
||||
self.size = 0
|
||||
# Move key-value pairs from the original hash table to the new hash table
|
||||
for bucket in buckets:
|
||||
for pair in bucket:
|
||||
self.put(pair.key, pair.val)
|
||||
|
||||
def print(self):
|
||||
"""Print hash table"""
|
||||
for bucket in self.buckets:
|
||||
res = []
|
||||
for pair in bucket:
|
||||
res.append(str(pair.key) + " -> " + pair.val)
|
||||
print(res)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize hash table
|
||||
hashmap = HashMapChaining()
|
||||
|
||||
# Add operation
|
||||
# Add key-value pair (key, value) to the hash table
|
||||
hashmap.put(12836, "Ha")
|
||||
hashmap.put(15937, "Luo")
|
||||
hashmap.put(16750, "Suan")
|
||||
hashmap.put(13276, "Fa")
|
||||
hashmap.put(10583, "Ya")
|
||||
print("\nAfter adding, the hash table is\n[Key1 -> Value1, Key2 -> Value2, ...]")
|
||||
hashmap.print()
|
||||
|
||||
# Query operation
|
||||
# Enter key to the hash table, get value
|
||||
name = hashmap.get(13276)
|
||||
print("\nEnter student ID 13276, found name " + name)
|
||||
|
||||
# Remove operation
|
||||
# Remove key-value pair (key, value) from the hash table
|
||||
hashmap.remove(12836)
|
||||
print("\nAfter removing 12836, the hash table is\n[Key1 -> Value1, Key2 -> Value2, ...]")
|
||||
hashmap.print()
|
||||
138
en/codes/python/chapter_hashing/hash_map_open_addressing.py
Normal file
138
en/codes/python/chapter_hashing/hash_map_open_addressing.py
Normal file
@ -0,0 +1,138 @@
|
||||
"""
|
||||
File: hash_map_open_addressing.py
|
||||
Created Time: 2023-06-13
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from chapter_hashing.array_hash_map import Pair
|
||||
|
||||
|
||||
class HashMapOpenAddressing:
|
||||
"""Open addressing hash table"""
|
||||
|
||||
def __init__(self):
|
||||
"""Constructor"""
|
||||
self.size = 0 # Number of key-value pairs
|
||||
self.capacity = 4 # Hash table capacity
|
||||
self.load_thres = 2.0 / 3.0 # Load factor threshold for triggering expansion
|
||||
self.extend_ratio = 2 # Expansion multiplier
|
||||
self.buckets: list[Pair | None] = [None] * self.capacity # Bucket array
|
||||
self.TOMBSTONE = Pair(-1, "-1") # Removal mark
|
||||
|
||||
def hash_func(self, key: int) -> int:
|
||||
"""Hash function"""
|
||||
return key % self.capacity
|
||||
|
||||
def load_factor(self) -> float:
|
||||
"""Load factor"""
|
||||
return self.size / self.capacity
|
||||
|
||||
def find_bucket(self, key: int) -> int:
|
||||
"""Search for the bucket index corresponding to key"""
|
||||
index = self.hash_func(key)
|
||||
first_tombstone = -1
|
||||
# Linear probing, break when encountering an empty bucket
|
||||
while self.buckets[index] is not None:
|
||||
# If the key is encountered, return the corresponding bucket index
|
||||
if self.buckets[index].key == key:
|
||||
# If a removal mark was encountered earlier, move the key-value pair to that index
|
||||
if first_tombstone != -1:
|
||||
self.buckets[first_tombstone] = self.buckets[index]
|
||||
self.buckets[index] = self.TOMBSTONE
|
||||
return first_tombstone # Return the moved bucket index
|
||||
return index # Return bucket index
|
||||
# Record the first encountered removal mark
|
||||
if first_tombstone == -1 and self.buckets[index] is self.TOMBSTONE:
|
||||
first_tombstone = index
|
||||
# Calculate the bucket index, return to the head if exceeding the tail
|
||||
index = (index + 1) % self.capacity
|
||||
# If the key does not exist, return the index of the insertion point
|
||||
return index if first_tombstone == -1 else first_tombstone
|
||||
|
||||
def get(self, key: int) -> str:
|
||||
"""Query operation"""
|
||||
# Search for the bucket index corresponding to key
|
||||
index = self.find_bucket(key)
|
||||
# If the key-value pair is found, return the corresponding val
|
||||
if self.buckets[index] not in [None, self.TOMBSTONE]:
|
||||
return self.buckets[index].val
|
||||
# If the key-value pair does not exist, return None
|
||||
return None
|
||||
|
||||
def put(self, key: int, val: str):
|
||||
"""Add operation"""
|
||||
# When the load factor exceeds the threshold, perform expansion
|
||||
if self.load_factor() > self.load_thres:
|
||||
self.extend()
|
||||
# Search for the bucket index corresponding to key
|
||||
index = self.find_bucket(key)
|
||||
# If the key-value pair is found, overwrite val and return
|
||||
if self.buckets[index] not in [None, self.TOMBSTONE]:
|
||||
self.buckets[index].val = val
|
||||
return
|
||||
# If the key-value pair does not exist, add the key-value pair
|
||||
self.buckets[index] = Pair(key, val)
|
||||
self.size += 1
|
||||
|
||||
def remove(self, key: int):
|
||||
"""Remove operation"""
|
||||
# Search for the bucket index corresponding to key
|
||||
index = self.find_bucket(key)
|
||||
# If the key-value pair is found, cover it with a removal mark
|
||||
if self.buckets[index] not in [None, self.TOMBSTONE]:
|
||||
self.buckets[index] = self.TOMBSTONE
|
||||
self.size -= 1
|
||||
|
||||
def extend(self):
|
||||
"""Extend hash table"""
|
||||
# Temporarily store the original hash table
|
||||
buckets_tmp = self.buckets
|
||||
# Initialize the extended new hash table
|
||||
self.capacity *= self.extend_ratio
|
||||
self.buckets = [None] * self.capacity
|
||||
self.size = 0
|
||||
# Move key-value pairs from the original hash table to the new hash table
|
||||
for pair in buckets_tmp:
|
||||
if pair not in [None, self.TOMBSTONE]:
|
||||
self.put(pair.key, pair.val)
|
||||
|
||||
def print(self):
|
||||
"""Print hash table"""
|
||||
for pair in self.buckets:
|
||||
if pair is None:
|
||||
print("None")
|
||||
elif pair is self.TOMBSTONE:
|
||||
print("TOMBSTONE")
|
||||
else:
|
||||
print(pair.key, "->", pair.val)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize hash table
|
||||
hashmap = HashMapOpenAddressing()
|
||||
|
||||
# Add operation
|
||||
# Add key-value pair (key, val) to the hash table
|
||||
hashmap.put(12836, "Ha")
|
||||
hashmap.put(15937, "Luo")
|
||||
hashmap.put(16750, "Suan")
|
||||
hashmap.put(13276, "Fa")
|
||||
hashmap.put(10583, "Ya")
|
||||
print("\nAfter adding, the hash table is\nKey -> Value")
|
||||
hashmap.print()
|
||||
|
||||
# Query operation
|
||||
# Enter key to the hash table, get value val
|
||||
name = hashmap.get(13276)
|
||||
print("\nEnter student ID 13276, found name " + name)
|
||||
|
||||
# Remove operation
|
||||
# Remove key-value pair (key, val) from the hash table
|
||||
hashmap.remove(16750)
|
||||
print("\nAfter removing 16750, the hash table is\nKey -> Value")
|
||||
hashmap.print()
|
||||
58
en/codes/python/chapter_hashing/simple_hash.py
Normal file
58
en/codes/python/chapter_hashing/simple_hash.py
Normal file
@ -0,0 +1,58 @@
|
||||
"""
|
||||
File: simple_hash.py
|
||||
Created Time: 2023-06-15
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def add_hash(key: str) -> int:
|
||||
"""Additive hash"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash += ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
def mul_hash(key: str) -> int:
|
||||
"""Multiplicative hash"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash = 31 * hash + ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
def xor_hash(key: str) -> int:
|
||||
"""XOR hash"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash ^= ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
def rot_hash(key: str) -> int:
|
||||
"""Rotational hash"""
|
||||
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 algorithm"
|
||||
|
||||
hash = add_hash(key)
|
||||
print(f"Additive hash value is {hash}")
|
||||
|
||||
hash = mul_hash(key)
|
||||
print(f"Multiplicative hash value is {hash}")
|
||||
|
||||
hash = xor_hash(key)
|
||||
print(f"XOR hash value is {hash}")
|
||||
|
||||
hash = rot_hash(key)
|
||||
print(f"Rotational hash value is {hash}")
|
||||
Reference in New Issue
Block a user