mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-11 16:32:00 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -14,11 +14,11 @@ class Pair:
|
||||
|
||||
|
||||
class ArrayHashMap:
|
||||
"""Hash table based on array implementation"""
|
||||
"""Hash table implemented with an array"""
|
||||
|
||||
def __init__(self):
|
||||
"""Constructor"""
|
||||
# Initialize array with 100 buckets
|
||||
# Initialize an array containing 100 buckets
|
||||
self.buckets: list[Pair | None] = [None] * 100
|
||||
|
||||
def hash_func(self, key: int) -> int:
|
||||
@@ -27,7 +27,7 @@ class ArrayHashMap:
|
||||
return index
|
||||
|
||||
def get(self, key: int) -> str | None:
|
||||
"""Query operation"""
|
||||
"""Lookup operation"""
|
||||
index: int = self.hash_func(key)
|
||||
pair: Pair = self.buckets[index]
|
||||
if pair is None:
|
||||
@@ -35,7 +35,7 @@ class ArrayHashMap:
|
||||
return pair.val
|
||||
|
||||
def put(self, key: int, val: str):
|
||||
"""Add and update operation"""
|
||||
"""Insert and update operations"""
|
||||
pair = Pair(key, val)
|
||||
index: int = self.hash_func(key)
|
||||
self.buckets[index] = pair
|
||||
@@ -43,7 +43,7 @@ class ArrayHashMap:
|
||||
def remove(self, key: int):
|
||||
"""Remove operation"""
|
||||
index: int = self.hash_func(key)
|
||||
# Set to None to represent removal
|
||||
# Set to None to mark removal
|
||||
self.buckets[index] = None
|
||||
|
||||
def entry_set(self) -> list[Pair]:
|
||||
@@ -71,47 +71,47 @@ class ArrayHashMap:
|
||||
return result
|
||||
|
||||
def print(self):
|
||||
"""Print hash table"""
|
||||
"""Print the hash table"""
|
||||
for pair in self.buckets:
|
||||
if pair is not None:
|
||||
print(pair.key, "->", pair.val)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize hash table
|
||||
# Initialize the hash table
|
||||
hmap = ArrayHashMap()
|
||||
|
||||
# Add operation
|
||||
# Add key-value pair (key, value) to the hash table
|
||||
hmap.put(12836, "Xiao Ha")
|
||||
hmap.put(15937, "Xiao Luo")
|
||||
hmap.put(16750, "Xiao Suan")
|
||||
hmap.put(13276, "Xiao Fa")
|
||||
hmap.put(10583, "Xiao Ya")
|
||||
print("\nAfter adding, the hash table is\nKey -> Value")
|
||||
# Insert operation
|
||||
# Insert the key-value pair (key, value) into the hash table
|
||||
hmap.put(12836, "小哈")
|
||||
hmap.put(15937, "小啰")
|
||||
hmap.put(16750, "小算")
|
||||
hmap.put(13276, "小法")
|
||||
hmap.put(10583, "小鸭")
|
||||
print("\nHash table after insertion:\nKey -> Value")
|
||||
hmap.print()
|
||||
|
||||
# Query operation
|
||||
# Input key into the hash table to get value
|
||||
# Lookup operation
|
||||
# Look up key in the hash table to obtain value
|
||||
name = hmap.get(15937)
|
||||
print("\nInput student ID 15937, found name " + name)
|
||||
print("\nLook up student ID 15937 to obtain the name " + name)
|
||||
|
||||
# Remove operation
|
||||
# Remove key-value pair (key, value) from the hash table
|
||||
# Remove the key-value pair (key, value) from the hash table
|
||||
hmap.remove(10583)
|
||||
print("\nAfter removing 10583, the hash table is\nKey -> Value")
|
||||
print("\nHash table after removing 10583:\nKey -> Value")
|
||||
hmap.print()
|
||||
|
||||
# Traverse hash table
|
||||
print("\nTraverse key-value pairs Key->Value")
|
||||
# Traverse the hash table
|
||||
print("\nTraverse key-value pairs: Key->Value")
|
||||
for pair in hmap.entry_set():
|
||||
print(pair.key, "->", pair.val)
|
||||
|
||||
print("\nTraverse keys only Key")
|
||||
print("\nTraverse keys only: Key")
|
||||
for key in hmap.key_set():
|
||||
print(key)
|
||||
|
||||
print("\nTraverse values only Value")
|
||||
print("\nTraverse values only: Value")
|
||||
for val in hmap.value_set():
|
||||
print(val)
|
||||
|
||||
@@ -10,28 +10,28 @@ from pathlib import Path
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import ListNode
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
num = 3
|
||||
hash_num = hash(num)
|
||||
print(f"Hash value of integer {num} is {hash_num}")
|
||||
print(f"Hash value of integer {num}: {hash_num}")
|
||||
|
||||
bol = True
|
||||
hash_bol = hash(bol)
|
||||
print(f"Hash value of boolean {bol} is {hash_bol}")
|
||||
print(f"Hash value of Boolean {bol}: {hash_bol}")
|
||||
|
||||
dec = 3.14159
|
||||
hash_dec = hash(dec)
|
||||
print(f"Hash value of decimal {dec} is {hash_dec}")
|
||||
print(f"Hash value of floating-point number {dec}: {hash_dec}")
|
||||
|
||||
str = "Hello algo"
|
||||
str = "Hello 算法"
|
||||
hash_str = hash(str)
|
||||
print(f"Hash value of string {str} is {hash_str}")
|
||||
print(f"Hash value of string {str}: {hash_str}")
|
||||
|
||||
tup = (12836, "Xiao Ha")
|
||||
tup = (12836, "小哈")
|
||||
hash_tup = hash(tup)
|
||||
print(f"Hash value of tuple {tup} is {hash(hash_tup)}")
|
||||
print(f"Hash of the hash value of tuple {tup}: {hash(hash_tup)}")
|
||||
|
||||
obj = ListNode(0)
|
||||
hash_obj = hash(obj)
|
||||
print(f"Hash value of node object {obj} is {hash_obj}")
|
||||
print(f"Hash value of node object {obj}: {hash_obj}")
|
||||
|
||||
@@ -10,41 +10,41 @@ from pathlib import Path
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import print_dict
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize hash table
|
||||
# Initialize the hash table
|
||||
hmap = dict[int, str]()
|
||||
|
||||
# Add operation
|
||||
# Add key-value pair (key, value) to the hash table
|
||||
hmap[12836] = "Xiao Ha"
|
||||
hmap[15937] = "Xiao Luo"
|
||||
hmap[16750] = "Xiao Suan"
|
||||
hmap[13276] = "Xiao Fa"
|
||||
hmap[10583] = "Xiao Ya"
|
||||
print("\nAfter adding, the hash table is\nKey -> Value")
|
||||
# Insert operation
|
||||
# Insert the key-value pair (key, value) into the hash table
|
||||
hmap[12836] = "小哈"
|
||||
hmap[15937] = "小啰"
|
||||
hmap[16750] = "小算"
|
||||
hmap[13276] = "小法"
|
||||
hmap[10583] = "小鸭"
|
||||
print("\nHash table after insertion:\nKey -> Value")
|
||||
print_dict(hmap)
|
||||
|
||||
# Query operation
|
||||
# Input key into the hash table to get value
|
||||
# Lookup operation
|
||||
# Look up key in the hash table to obtain value
|
||||
name: str = hmap[15937]
|
||||
print("\nInput student ID 15937, found name " + name)
|
||||
print("\nLook up student ID 15937 to obtain the name " + name)
|
||||
|
||||
# Remove operation
|
||||
# Remove key-value pair (key, value) from the hash table
|
||||
# Remove the key-value pair (key, value) from the hash table
|
||||
hmap.pop(10583)
|
||||
print("\nAfter removing 10583, the hash table is\nKey -> Value")
|
||||
print("\nHash table after removing 10583:\nKey -> Value")
|
||||
print_dict(hmap)
|
||||
|
||||
# Traverse hash table
|
||||
print("\nTraverse key-value pairs Key->Value")
|
||||
# Traverse the hash table
|
||||
print("\nTraverse key-value pairs: Key->Value")
|
||||
for key, value in hmap.items():
|
||||
print(key, "->", value)
|
||||
|
||||
print("\nTraverse keys only Key")
|
||||
print("\nTraverse keys only: Key")
|
||||
for key in hmap.keys():
|
||||
print(key)
|
||||
|
||||
print("\nTraverse values only Value")
|
||||
print("\nTraverse values only: Value")
|
||||
for val in hmap.values():
|
||||
print(val)
|
||||
|
||||
@@ -18,8 +18,8 @@ class HashMapChaining:
|
||||
"""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.load_thres = 2.0 / 3.0 # Load factor threshold that triggers capacity growth
|
||||
self.extend_ratio = 2 # Capacity growth factor
|
||||
self.buckets = [[] for _ in range(self.capacity)] # Bucket array
|
||||
|
||||
def hash_func(self, key: int) -> int:
|
||||
@@ -31,29 +31,29 @@ class HashMapChaining:
|
||||
return self.size / self.capacity
|
||||
|
||||
def get(self, key: int) -> str | None:
|
||||
"""Query operation"""
|
||||
"""Lookup operation"""
|
||||
index = self.hash_func(key)
|
||||
bucket = self.buckets[index]
|
||||
# Traverse bucket, if key is found, return corresponding val
|
||||
# Traverse the bucket; if key is found, return its corresponding val
|
||||
for pair in bucket:
|
||||
if pair.key == key:
|
||||
return pair.val
|
||||
# If key is not found, return None
|
||||
# Return None if key is not found
|
||||
return None
|
||||
|
||||
def put(self, key: int, val: str):
|
||||
"""Add operation"""
|
||||
# When load factor exceeds threshold, perform expansion
|
||||
"""Insert operation"""
|
||||
# Grow the capacity when the load factor exceeds the threshold
|
||||
if self.load_factor() > self.load_thres:
|
||||
self.extend()
|
||||
index = self.hash_func(key)
|
||||
bucket = self.buckets[index]
|
||||
# Traverse bucket, if specified key is encountered, update corresponding val and return
|
||||
# Traverse the bucket; if the specified key is found, update its val and return
|
||||
for pair in bucket:
|
||||
if pair.key == key:
|
||||
pair.val = val
|
||||
return
|
||||
# If key does not exist, append key-value pair to the end
|
||||
# If key is absent, append the key-value pair at the end
|
||||
pair = Pair(key, val)
|
||||
bucket.append(pair)
|
||||
self.size += 1
|
||||
@@ -62,7 +62,7 @@ class HashMapChaining:
|
||||
"""Remove operation"""
|
||||
index = self.hash_func(key)
|
||||
bucket = self.buckets[index]
|
||||
# Traverse bucket and remove key-value pair from it
|
||||
# Traverse the bucket and remove the key-value pair
|
||||
for pair in bucket:
|
||||
if pair.key == key:
|
||||
bucket.remove(pair)
|
||||
@@ -70,20 +70,20 @@ class HashMapChaining:
|
||||
break
|
||||
|
||||
def extend(self):
|
||||
"""Expand hash table"""
|
||||
# Temporarily store the original hash table
|
||||
"""Grow the hash table capacity"""
|
||||
# Keep a reference to the original hash table
|
||||
buckets = self.buckets
|
||||
# Initialize expanded new hash table
|
||||
# Initialize a new hash table with the expanded capacity
|
||||
self.capacity *= self.extend_ratio
|
||||
self.buckets = [[] for _ in range(self.capacity)]
|
||||
self.size = 0
|
||||
# Move key-value pairs from original hash table to new hash table
|
||||
# Move the key-value pairs from the original hash table to the new one
|
||||
for bucket in buckets:
|
||||
for pair in bucket:
|
||||
self.put(pair.key, pair.val)
|
||||
|
||||
def print(self):
|
||||
"""Print hash table"""
|
||||
"""Print the hash table"""
|
||||
for bucket in self.buckets:
|
||||
res = []
|
||||
for pair in bucket:
|
||||
@@ -91,28 +91,28 @@ class HashMapChaining:
|
||||
print(res)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize hash table
|
||||
# Initialize the hash table
|
||||
hashmap = HashMapChaining()
|
||||
|
||||
# Add operation
|
||||
# Add key-value pair (key, value) to the hash table
|
||||
hashmap.put(12836, "Xiao Ha")
|
||||
hashmap.put(15937, "Xiao Luo")
|
||||
hashmap.put(16750, "Xiao Suan")
|
||||
hashmap.put(13276, "Xiao Fa")
|
||||
hashmap.put(10583, "Xiao Ya")
|
||||
print("\nAfter adding, the hash table is\n[Key1 -> Value1, Key2 -> Value2, ...]")
|
||||
# Insert operation
|
||||
# Insert the key-value pair (key, value) into the hash table
|
||||
hashmap.put(12836, "小哈")
|
||||
hashmap.put(15937, "小啰")
|
||||
hashmap.put(16750, "小算")
|
||||
hashmap.put(13276, "小法")
|
||||
hashmap.put(10583, "小鸭")
|
||||
print("\nHash table after insertion:\n[Key1 -> Value1, Key2 -> Value2, ...]")
|
||||
hashmap.print()
|
||||
|
||||
# Query operation
|
||||
# Input key into the hash table to get value
|
||||
# Lookup operation
|
||||
# Look up key in the hash table to obtain value
|
||||
name = hashmap.get(13276)
|
||||
print("\nInput student ID 13276, found name " + name)
|
||||
print("\nLook up student ID 13276 to obtain the name " + name)
|
||||
|
||||
# Remove operation
|
||||
# Remove key-value pair (key, value) from the hash table
|
||||
# Remove the 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, ...]")
|
||||
print("\nHash table after removing 12836:\n[Key1 -> Value1, Key2 -> Value2, ...]")
|
||||
hashmap.print()
|
||||
|
||||
@@ -18,10 +18,10 @@ class HashMapOpenAddressing:
|
||||
"""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.load_thres = 2.0 / 3.0 # Load factor threshold that triggers capacity growth
|
||||
self.extend_ratio = 2 # Capacity growth factor
|
||||
self.buckets: list[Pair | None] = [None] * self.capacity # Bucket array
|
||||
self.TOMBSTONE = Pair(-1, "-1") # Removal marker
|
||||
self.TOMBSTONE = Pair(-1, "-1") # Tombstone marker
|
||||
|
||||
def hash_func(self, key: int) -> int:
|
||||
"""Hash function"""
|
||||
@@ -32,76 +32,76 @@ class HashMapOpenAddressing:
|
||||
return self.size / self.capacity
|
||||
|
||||
def find_bucket(self, key: int) -> int:
|
||||
"""Search for bucket index corresponding to key"""
|
||||
"""Find the bucket index for key"""
|
||||
index = self.hash_func(key)
|
||||
first_tombstone = -1
|
||||
# Linear probing, break when encountering an empty bucket
|
||||
# Probe linearly until an empty bucket is reached
|
||||
while self.buckets[index] is not None:
|
||||
# If key is encountered, return the corresponding bucket index
|
||||
# If key is found, return its bucket index
|
||||
if self.buckets[index].key == key:
|
||||
# If a removal marker was encountered before, move the key-value pair to that index
|
||||
# If a tombstone 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 removal marker encountered
|
||||
return first_tombstone # Return the bucket index after the move
|
||||
return index # Return the bucket index
|
||||
# Record the first tombstone encountered
|
||||
if first_tombstone == -1 and self.buckets[index] is self.TOMBSTONE:
|
||||
first_tombstone = index
|
||||
# Calculate bucket index, wrap around to the head if past the tail
|
||||
# Calculate the bucket index, wrapping to the beginning after the end
|
||||
index = (index + 1) % self.capacity
|
||||
# If key does not exist, return the index for insertion
|
||||
# If key is absent, return the index for insertion
|
||||
return index if first_tombstone == -1 else first_tombstone
|
||||
|
||||
def get(self, key: int) -> str:
|
||||
"""Query operation"""
|
||||
# Search for bucket index corresponding to key
|
||||
"""Lookup operation"""
|
||||
# Find the bucket index for key
|
||||
index = self.find_bucket(key)
|
||||
# If key-value pair is found, return corresponding val
|
||||
# If the key-value pair is found, return its val
|
||||
if self.buckets[index] not in [None, self.TOMBSTONE]:
|
||||
return self.buckets[index].val
|
||||
# If key-value pair does not exist, return None
|
||||
# Return None if the key-value pair is absent
|
||||
return None
|
||||
|
||||
def put(self, key: int, val: str):
|
||||
"""Add operation"""
|
||||
# When load factor exceeds threshold, perform expansion
|
||||
"""Insert operation"""
|
||||
# Grow the capacity when the load factor exceeds the threshold
|
||||
if self.load_factor() > self.load_thres:
|
||||
self.extend()
|
||||
# Search for bucket index corresponding to key
|
||||
# Find the bucket index for key
|
||||
index = self.find_bucket(key)
|
||||
# If key-value pair is found, overwrite val and return
|
||||
# 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 key-value pair does not exist, add the key-value pair
|
||||
# If the key-value pair is absent, insert it
|
||||
self.buckets[index] = Pair(key, val)
|
||||
self.size += 1
|
||||
|
||||
def remove(self, key: int):
|
||||
"""Remove operation"""
|
||||
# Search for bucket index corresponding to key
|
||||
# Find the bucket index for key
|
||||
index = self.find_bucket(key)
|
||||
# If key-value pair is found, overwrite it with removal marker
|
||||
# If the key-value pair is found, replace it with a tombstone
|
||||
if self.buckets[index] not in [None, self.TOMBSTONE]:
|
||||
self.buckets[index] = self.TOMBSTONE
|
||||
self.size -= 1
|
||||
|
||||
def extend(self):
|
||||
"""Expand hash table"""
|
||||
# Temporarily store the original hash table
|
||||
"""Grow the hash table capacity"""
|
||||
# Keep a reference to the original hash table
|
||||
buckets_tmp = self.buckets
|
||||
# Initialize expanded new hash table
|
||||
# Initialize a new hash table with the expanded capacity
|
||||
self.capacity *= self.extend_ratio
|
||||
self.buckets = [None] * self.capacity
|
||||
self.size = 0
|
||||
# Move key-value pairs from original hash table to new hash table
|
||||
# Move the key-value pairs from the original hash table to the new one
|
||||
for pair in buckets_tmp:
|
||||
if pair not in [None, self.TOMBSTONE]:
|
||||
self.put(pair.key, pair.val)
|
||||
|
||||
def print(self):
|
||||
"""Print hash table"""
|
||||
"""Print the hash table"""
|
||||
for pair in self.buckets:
|
||||
if pair is None:
|
||||
print("None")
|
||||
@@ -111,28 +111,28 @@ class HashMapOpenAddressing:
|
||||
print(pair.key, "->", pair.val)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize hash table
|
||||
# Initialize the hash table
|
||||
hashmap = HashMapOpenAddressing()
|
||||
|
||||
# Add operation
|
||||
# Add key-value pair (key, val) to the hash table
|
||||
hashmap.put(12836, "Xiao Ha")
|
||||
hashmap.put(15937, "Xiao Luo")
|
||||
hashmap.put(16750, "Xiao Suan")
|
||||
hashmap.put(13276, "Xiao Fa")
|
||||
hashmap.put(10583, "Xiao Ya")
|
||||
print("\nAfter adding, the hash table is\nKey -> Value")
|
||||
# Insert operation
|
||||
# Insert the key-value pair (key, val) into the hash table
|
||||
hashmap.put(12836, "小哈")
|
||||
hashmap.put(15937, "小啰")
|
||||
hashmap.put(16750, "小算")
|
||||
hashmap.put(13276, "小法")
|
||||
hashmap.put(10583, "小鸭")
|
||||
print("\nHash table after insertion:\nKey -> Value")
|
||||
hashmap.print()
|
||||
|
||||
# Query operation
|
||||
# Input key into the hash table to get val
|
||||
# Lookup operation
|
||||
# Look up key in the hash table to obtain val
|
||||
name = hashmap.get(13276)
|
||||
print("\nInput student ID 13276, found name " + name)
|
||||
print("\nLook up student ID 13276 to obtain the name " + name)
|
||||
|
||||
# Remove operation
|
||||
# Remove key-value pair (key, val) from the hash table
|
||||
# Remove the key-value pair (key, val) from the hash table
|
||||
hashmap.remove(16750)
|
||||
print("\nAfter removing 16750, the hash table is\nKey -> Value")
|
||||
print("\nHash table after removing 16750:\nKey -> Value")
|
||||
hashmap.print()
|
||||
|
||||
@@ -33,7 +33,7 @@ def xor_hash(key: str) -> int:
|
||||
|
||||
|
||||
def rot_hash(key: str) -> int:
|
||||
"""Rotational hash"""
|
||||
"""Rotating hash"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
@@ -41,18 +41,18 @@ def rot_hash(key: str) -> int:
|
||||
return hash % modulus
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
key = "Hello algo"
|
||||
key = "Hello 算法"
|
||||
|
||||
hash = add_hash(key)
|
||||
print(f"Additive hash value is {hash}")
|
||||
print(f"Additive hash value: {hash}")
|
||||
|
||||
hash = mul_hash(key)
|
||||
print(f"Multiplicative hash value is {hash}")
|
||||
print(f"Multiplicative hash value: {hash}")
|
||||
|
||||
hash = xor_hash(key)
|
||||
print(f"XOR hash value is {hash}")
|
||||
print(f"XOR hash value: {hash}")
|
||||
|
||||
hash = rot_hash(key)
|
||||
print(f"Rotational hash value is {hash}")
|
||||
print(f"Rotating hash value: {hash}")
|
||||
|
||||
Reference in New Issue
Block a user