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:
Yudong Jin
2026-10-31 03:35:51 +08:00
committed by GitHub
parent ef46e2ed95
commit 14c314c08c
1502 changed files with 29459 additions and 23517 deletions

View File

@@ -1,60 +1,60 @@
# Hash Algorithm
# Hash algorithms
The previous two sections introduced the working principle of hash tables and the methods to handle hash collisions. However, both open addressing and separate chaining **can only ensure that the hash table functions normally when hash collisions occur, but cannot reduce the frequency of hash collisions**.
The previous two sections explained how hash tables work and how collisions are resolved. Whether we use open addressing or separate chaining, **these techniques keep the table working when collisions occur, but do not reduce how often collisions happen**.
If hash collisions occur too frequently, the performance of the hash table will deteriorate drastically. As shown in the figure below, for a separate chaining hash table, in the ideal case, the key-value pairs are evenly distributed across the buckets, achieving optimal query efficiency; in the worst case, all key-value pairs are stored in the same bucket, degrading the time complexity to $O(n)$.
Frequent collisions can severely degrade performance. In the separate-chaining table shown below, the ideal case distributes pairs evenly among buckets for the best lookup efficiency. In the worst case, all pairs occupy the same bucket, degrading the time complexity to $O(n)$.
![Ideal and worst cases of hash collisions](hash_algorithm.assets/hash_collision_best_worst_condition.png)
![Best and worst cases for hash collisions](hash_algorithm.assets/hash_collision_best_worst_condition.png)
**The distribution of key-value pairs is determined by the hash function**. Recall the steps of the hash function: first compute the hash value, then take it modulo the array length:
**The hash function determines how key-value pairs are distributed**. Recall its two steps: calculate a hash value, then take it modulo the array length:
```shell
index = hash(key) % capacity
```
Observing the above formula, when the hash table capacity `capacity` is fixed, **the hash algorithm `hash()` determines the output value**, thereby determining the distribution of key-value pairs in the hash table.
For a fixed `capacity`, **the hash algorithm `hash()` determines the output**, and therefore the distribution of pairs in the table.
This means that, to reduce the probability of hash collisions, we should focus on the design of the hash algorithm `hash()`.
To lower the likelihood of collisions, we should therefore focus on designing `hash()`.
## Goals of Hash Algorithms
## Goals of a hash algorithm
To build a hash table that is both fast and robust, a hash algorithm should have the following properties:
To build a hash table that is both fast and reliable, its hash algorithm should have these properties.
- **Determinism**: For the same input, the hash algorithm should always produce the same output. Only then can the hash table be reliable.
- **High efficiency**: The process of computing the hash value should be fast enough. The smaller the computational overhead, the more practical the hash table.
- **Uniform distribution**: The hash algorithm should ensure that key-value pairs are evenly distributed in the hash table. The more uniform the distribution, the lower the probability of hash collisions.
- **Determinism**: The same input must always produce the same output, ensuring reliable lookup.
- **Efficiency**: Calculating a hash should be fast. Lower computational overhead makes the table more practical.
- **Uniform distribution**: The algorithm should distribute pairs evenly across the table. More uniform distribution means fewer collisions.
In fact, hash algorithms are not only used to implement hash tables but are also widely applied in other fields.
Hash algorithms also have many applications beyond hash tables.
- **Password storage**: To protect the security of user passwords, systems usually do not store the plaintext passwords but rather the hash values of the passwords. When a user enters a password, the system calculates the hash value of the input and compares it with the stored hash value. If they match, the password is considered correct.
- **Data integrity check**: The data sender can calculate the hash value of the data and send it along; the receiver can recalculate the hash value of the received data and compare it with the received hash value. If they match, the data is considered intact.
- **Password storage**: To protect passwords, systems usually store password hashes rather than plaintext passwords. When a user enters a password, the system hashes it and compares the result with the stored hash. A match means the password is accepted.
- **Data-integrity checking**: A sender can calculate a hash of the data and send it alongside the data. The receiver recomputes the hash and compares it with the received hash. A match indicates that the data is intact.
For cryptographic applications, hash algorithms need stronger security properties to prevent reverse engineering, such as inferring the original password from a hash value.
Cryptographic applications require stronger security properties to prevent reverse engineering, such as recovering an original password from its hash.
- **Unidirectionality**: It should be impossible to deduce any information about the input data from the hash value.
- **Collision resistance**: It should be extremely difficult to find two different inputs that produce the same hash value.
- **Avalanche effect**: Minor changes in the input should lead to significant and unpredictable changes in the output.
- **One-wayness**: The hash should not reveal any information about the input data.
- **Collision resistance**: Finding two different inputs with the same hash should be extremely difficult.
- **Avalanche effect**: A small input change should produce a large, unpredictable output change.
Note that **"uniform distribution" and "collision resistance" are two independent concepts**. Satisfying uniform distribution does not necessarily mean collision resistance. For example, under random input `key`, the hash function `key % 100` can produce a uniformly distributed output. However, this hash algorithm is too simple, and all `key` with the same last two digits will have the same output, making it easy to deduce a usable `key` from the hash value, thereby cracking the password.
**Uniform distribution and collision resistance are independent concepts**. Uniform output does not guarantee collision resistance. For example, with random keys, `key % 100` can produce uniform outputs. But this algorithm is too simple: all keys with the same last two digits give the same output. It is therefore easy to infer a usable key from a hash and crack a password.
## Design of Hash Algorithms
## Designing a hash algorithm
The design of hash algorithms is a complex issue that requires consideration of many factors. However, for some less demanding scenarios, we can also design some simple hash algorithms.
Designing a hash algorithm is complex and involves many factors. For less demanding uses, however, we can devise simple algorithms.
- **Additive hash**: Add up the ASCII codes of each character in the input and use the total sum as the hash value.
- **Multiplicative hash**: Leverage the low correlation introduced by multiplication: multiply by a constant at each step and accumulate the ASCII codes of the characters into the hash value.
- **XOR hash**: Accumulate the hash value by XORing each element of the input data.
- **Rotating hash**: Accumulate the ASCII code of each character into a hash value, performing a rotation operation on the hash value before each accumulation.
- **Additive hashing**: Add the ASCII codes of all input characters and use the sum as the hash.
- **Multiplicative hashing**: Use multiplication to mix values, multiplying by a constant each round and accumulating character ASCII codes into the hash.
- **XOR hashing**: Accumulate each input element into a hash using exclusive OR.
- **Rotational hashing**: Accumulate each character's ASCII code into a hash, rotating the hash before each accumulation.
```src
[file]{simple_hash}-[class]{}-[func]{rot_hash}
```
We can observe that the final step of each hash algorithm is to take the result modulo the large prime $1000000007$, ensuring that the hash value stays within a suitable range. This naturally raises a question: why emphasize using a prime modulus, and what are the drawbacks of using a composite modulus?
Each algorithm ends by taking the result modulo the large prime $1000000007$ to keep it within a suitable range. Why emphasize a prime modulus? What goes wrong with a composite modulus? This is an interesting question.
In short: **using a large prime as the modulus helps maximize the uniformity of hash values**. Because a prime shares no common factors with other numbers, it can reduce periodic patterns introduced by the modulo operation and thus mitigate hash collisions.
The conclusion is that **using a large prime modulus helps make hash values as uniformly distributed as possible**. Because a prime shares no nontrivial factors with other numbers, it reduces periodic patterns introduced by the modulo operation and thus avoids collisions.
For example, suppose we choose the composite number $9$ as the modulus, which can be divided by $3$, then all `key` divisible by $3$ will be mapped to hash values $0$, $3$, $6$.
For example, choose the composite modulus $9$, which is divisible by $3$. Every key divisible by $3$ then maps to one of just three hash values: $0$, $3$, or $6$.
$$
\begin{aligned}
@@ -64,7 +64,7 @@ $$
\end{aligned}
$$
If the input `key` values happen to follow this kind of arithmetic progression, the hash values will cluster, worsening hash collisions. Now suppose we replace `modulus` with the prime number $13$. Because `key` and `modulus` share no common factors, the output hash values become much more evenly distributed.
If the input keys follow this arithmetic progression, the hash values cluster, increasing collisions. Now replace the modulus with the prime $13$. With no common factor between the key pattern and the modulus, the output becomes noticeably more uniform.
$$
\begin{aligned}
@@ -74,71 +74,71 @@ $$
\end{aligned}
$$
It is worth noting that if the `key` is guaranteed to be randomly and uniformly distributed, then choosing a prime number or a composite number as the modulus can both produce uniformly distributed hash values. However, when the distribution of `key` has some periodicity, modulo a composite number is more likely to result in clustering.
If the keys are already uniformly random, either a prime or a composite modulus can produce uniformly distributed hashes. When the keys have a periodic pattern, however, a composite modulus is more likely to cause clustering.
In summary, we usually choose a prime number as the modulus, and this prime number should be large enough to eliminate periodic patterns as much as possible, enhancing the robustness of the hash algorithm.
We therefore usually choose a prime modulus, preferably a large one, to suppress periodic patterns as much as possible and make the algorithm more robust.
## Common Hash Algorithms
## Common hash algorithms
It is easy to see that the simple hash algorithms introduced above are fairly "fragile" and fall far short of the design goals of hash algorithms. For example, because addition and XOR are commutative, additive hash and XOR hash cannot distinguish strings with the same characters in a different order, which may worsen hash collisions and introduce security risks.
The simple algorithms above are fragile and fall well short of our design goals. Addition and XOR are commutative, for example, so additive and XOR hashing cannot distinguish strings containing the same characters in different orders. This can increase collisions and create security problems.
In practice, we usually use some standard hash algorithms, such as MD5, SHA-1, SHA-2, and SHA-3. They can map input data of any length to a fixed-length hash value.
In practice, standard algorithms such as MD5, SHA-1, SHA-2, and SHA-3 are commonly used. They map inputs of arbitrary length to fixed-length hash values.
Over the past century, hash algorithms have been in a continuous process of upgrading and optimization. Some researchers strive to improve the performance of hash algorithms, while others, including hackers, are dedicated to finding security issues in hash algorithms. The table below shows hash algorithms commonly used in practical applications.
Over nearly a century, hash algorithms have continually evolved. Some researchers work to improve their performance, while others, along with hackers, search for security weaknesses. The table below lists commonly used algorithms.
- MD5 and SHA-1 have been successfully attacked multiple times and are thus abandoned in various security applications.
- SHA-2 series, especially SHA-256, is one of the most secure hash algorithms to date, with no successful attacks reported, hence commonly used in various security applications and protocols.
- SHA-3 has lower implementation costs and higher computational efficiency compared to SHA-2, but its current usage coverage is not as extensive as the SHA-2 series.
- MD5 and SHA-1 have been successfully attacked repeatedly and have been retired from security applications.
- SHA-256, part of the SHA-2 family, is among the most secure hash algorithms. No successful attack has been reported, so it is widely used in security applications and protocols.
- SHA-3 has lower implementation overhead and higher computational efficiency than SHA-2, but is not yet as widely used.
<p align="center"> Table <id> &nbsp; Common hash algorithms </p>
| | MD5 | SHA-1 | SHA-2 | SHA-3 |
| --------------- | ----------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------- | ---------------------------- |
| Release Year | 1992 | 1995 | 2002 | 2008 |
| Output Length | 128 bit | 160 bit | 256/512 bit | 224/256/384/512 bit |
| Hash Collisions | Frequent | Frequent | Rare | Rare |
| Security Level | Low, has been successfully attacked | Low, has been successfully attacked | High | High |
| Applications | Abandoned, still used for data integrity checks | Abandoned | Cryptocurrency transaction verification, digital signatures, etc. | Can be used to replace SHA-2 |
| | MD5 | SHA-1 | SHA-2 | SHA-3 |
| -------- | ------------------------------ | ---------------- | ---------------------------- | ------------------- |
| Introduced | 1992 | 1995 | 2002 | 2008 |
| Output length | 128 bit | 160 bit | 256/512 bit | 224/256/384/512 bit |
| Hash collisions | More frequent | More frequent | Rare | Rare |
| Security | Low; successfully attacked | Low; successfully attacked | High | High |
| Applications | Deprecated; still used for integrity checks | Deprecated | Cryptocurrency transaction verification, digital signatures, and more | Can replace SHA-2 |
## Hash Values in Data Structures
## Hash values of data structures
We know that hash table keys can be integers, floating-point numbers, strings, and other data types. Programming languages usually provide built-in hash algorithms for these types to compute bucket indices in a hash table. Taking Python as an example, we can call the `hash()` function to compute hash values for various data types.
Hash-table keys can be integers, floating-point numbers, strings, and other types. Programming languages usually provide built-in hashing for these types to calculate bucket indices. In Python, for example, `hash()` calculates hash values for various types.
- The hash values of integers and booleans are their own values.
- The calculation of hash values for floating-point numbers and strings is more complex, and interested readers are encouraged to study this on their own.
- The hash value of a tuple is obtained by hashing each of its elements and combining those results into a single hash value.
- An object's hash value is typically generated from its memory address. By overriding the object's hash method, it can instead be generated from the object's contents.
- Integers and Booleans have hash values equal to their own values.
- Hashing floating-point numbers and strings is more complex; interested readers can explore the details.
- A tuple's hash combines the hashes of its individual elements into one value.
- An object's hash is based on its memory address. Overriding its hash method allows hashing by content instead.
!!! tip
Be aware that the definition and methods of the built-in hash value calculation functions in different programming languages vary.
Built-in hash functions differ in their definitions and implementations across programming languages.
=== "Python"
```python title="built_in_hash.py"
num = 3
hash_num = hash(num)
# Hash value of integer 3 is 3
# The hash of the integer 3 is 3
bol = True
hash_bol = hash(bol)
# Hash value of boolean True is 1
# The hash of the Boolean True is 1
dec = 3.14159
hash_dec = hash(dec)
# Hash value of decimal 3.14159 is 326484311674566659
# The hash of the floating-point number 3.14159 is 326484311674566659
str = "Hello 算法"
hash_str = hash(str)
# Hash value of string "Hello 算法" is 4617003410720528961
# The hash of the string “Hello 算法” is 4617003410720528961
tup = (12836, "小哈")
hash_tup = hash(tup)
# Hash value of tuple (12836, '小哈') is 1029005403108185979
# The hash of the tuple (12836, '小哈') is 1029005403108185979
obj = ListNode(0)
hash_obj = hash(obj)
# Hash value of ListNode object at 0x1058fd810 is 274267521
# The hash of the node object <ListNode object at 0x1058fd810> is 274267521
```
=== "C++"
@@ -146,22 +146,22 @@ We know that hash table keys can be integers, floating-point numbers, strings, a
```cpp title="built_in_hash.cpp"
int num = 3;
size_t hashNum = hash<int>()(num);
// Hash value of integer 3 is 3
// The hash of the integer 3 is 3
bool bol = true;
size_t hashBol = hash<bool>()(bol);
// Hash value of boolean 1 is 1
// The hash of the Boolean 1 is 1
double dec = 3.14159;
size_t hashDec = hash<double>()(dec);
// Hash value of decimal 3.14159 is 4614256650576692846
// The hash of the floating-point number 3.14159 is 4614256650576692846
string str = "Hello 算法";
size_t hashStr = hash<string>()(str);
// Hash value of string "Hello 算法" is 15466937326284535026
// The hash of the string “Hello 算法” is 15466937326284535026
// In C++, built-in std::hash() only provides hash values for basic data types
// Hash values for arrays and objects need to be implemented separately
// In C++, built-in std::hash() provides hashing only for basic data types
// Hashing for arrays and objects must be implemented separately
```
=== "Java"
@@ -169,27 +169,27 @@ We know that hash table keys can be integers, floating-point numbers, strings, a
```java title="built_in_hash.java"
int num = 3;
int hashNum = Integer.hashCode(num);
// Hash value of integer 3 is 3
// The hash of the integer 3 is 3
boolean bol = true;
int hashBol = Boolean.hashCode(bol);
// Hash value of boolean true is 1231
// The hash of the Boolean true is 1231
double dec = 3.14159;
int hashDec = Double.hashCode(dec);
// Hash value of decimal 3.14159 is -1340954729
// The hash of the floating-point number 3.14159 is -1340954729
String str = "Hello 算法";
int hashStr = str.hashCode();
// Hash value of string "Hello 算法" is -727081396
// The hash of the string “Hello 算法” is -727081396
Object[] arr = { 12836, "小哈" };
int hashTup = Arrays.hashCode(arr);
// Hash value of array [12836, 小哈] is 1151158
// The hash of the array [12836, 小哈] is 1151158
ListNode obj = new ListNode(0);
int hashObj = obj.hashCode();
// Hash value of ListNode object utils.ListNode@7dc5e7b4 is 2110121908
// The hash of the node object utils.ListNode@7dc5e7b4 is 2110121908
```
=== "C#"
@@ -197,33 +197,33 @@ We know that hash table keys can be integers, floating-point numbers, strings, a
```csharp title="built_in_hash.cs"
int num = 3;
int hashNum = num.GetHashCode();
// Hash value of integer 3 is 3;
// The hash of the integer 3 is 3;
bool bol = true;
int hashBol = bol.GetHashCode();
// Hash value of boolean true is 1;
// The hash of the Boolean true is 1;
double dec = 3.14159;
int hashDec = dec.GetHashCode();
// Hash value of decimal 3.14159 is -1340954729;
// The hash of the floating-point number 3.14159 is -1340954729;
string str = "Hello 算法";
int hashStr = str.GetHashCode();
// Hash value of string "Hello 算法" is -586107568;
// The hash of the string “Hello 算法” is -586107568;
object[] arr = [12836, "小哈"];
int hashTup = arr.GetHashCode();
// Hash value of array [12836, 小哈] is 42931033;
// The hash of the array [12836, 小哈] is 42931033;
ListNode obj = new(0);
int hashObj = obj.GetHashCode();
// Hash value of ListNode object 0 is 39053774;
// The hash of the node object 0 is 39053774;
```
=== "Go"
```go title="built_in_hash.go"
// Go does not provide built-in hash code functions
// Go provides no built-in hash-code function
```
=== "Swift"
@@ -231,39 +231,39 @@ We know that hash table keys can be integers, floating-point numbers, strings, a
```swift title="built_in_hash.swift"
let num = 3
let hashNum = num.hashValue
// Hash value of integer 3 is 9047044699613009734
// The hash of the integer 3 is 9047044699613009734
let bol = true
let hashBol = bol.hashValue
// Hash value of boolean true is -4431640247352757451
// The hash of the Boolean true is -4431640247352757451
let dec = 3.14159
let hashDec = dec.hashValue
// Hash value of decimal 3.14159 is -2465384235396674631
// The hash of the floating-point number 3.14159 is -2465384235396674631
let str = "Hello 算法"
let hashStr = str.hashValue
// Hash value of string "Hello 算法" is -7850626797806988787
// The hash of the string “Hello 算法” is -7850626797806988787
let arr = [AnyHashable(12836), AnyHashable("小哈")]
let hashTup = arr.hashValue
// Hash value of array [AnyHashable(12836), AnyHashable("小哈")] is -2308633508154532996
// The hash of the array [AnyHashable(12836), AnyHashable("小哈")] is -2308633508154532996
let obj = ListNode(x: 0)
let hashObj = obj.hashValue
// Hash value of ListNode object utils.ListNode is -2434780518035996159
// The hash of the node object utils.ListNode is -2434780518035996159
```
=== "JS"
```javascript title="built_in_hash.js"
// JavaScript does not provide built-in hash code functions
// JavaScript provides no built-in hash-code function
```
=== "TS"
```typescript title="built_in_hash.ts"
// TypeScript does not provide built-in hash code functions
// TypeScript provides no built-in hash-code function
```
=== "Dart"
@@ -271,27 +271,27 @@ We know that hash table keys can be integers, floating-point numbers, strings, a
```dart title="built_in_hash.dart"
int num = 3;
int hashNum = num.hashCode;
// Hash value of integer 3 is 34803
// The hash of the integer 3 is 34803
bool bol = true;
int hashBol = bol.hashCode;
// Hash value of boolean true is 1231
// The hash of the Boolean true is 1231
double dec = 3.14159;
int hashDec = dec.hashCode;
// Hash value of decimal 3.14159 is 2570631074981783
// The hash of the floating-point number 3.14159 is 2570631074981783
String str = "Hello 算法";
int hashStr = str.hashCode;
// Hash value of string "Hello 算法" is 468167534
// The hash of the string “Hello 算法” is 468167534
List arr = [12836, "小哈"];
int hashArr = arr.hashCode;
// Hash value of array [12836, 小哈] is 976512528
// The hash of the array [12836, 小哈] is 976512528
ListNode obj = new ListNode(0);
int hashObj = obj.hashCode;
// Hash value of ListNode object Instance of 'ListNode' is 1033450432
// The hash of the node object Instance of 'ListNode' is 1033450432
```
=== "Rust"
@@ -304,43 +304,43 @@ We know that hash table keys can be integers, floating-point numbers, strings, a
let mut num_hasher = DefaultHasher::new();
num.hash(&mut num_hasher);
let hash_num = num_hasher.finish();
// Hash value of integer 3 is 568126464209439262
// The hash of the integer 3 is 568126464209439262
let bol = true;
let mut bol_hasher = DefaultHasher::new();
bol.hash(&mut bol_hasher);
let hash_bol = bol_hasher.finish();
// Hash value of boolean true is 4952851536318644461
// The hash of the Boolean true is 4952851536318644461
let dec: f32 = 3.14159;
let mut dec_hasher = DefaultHasher::new();
dec.to_bits().hash(&mut dec_hasher);
let hash_dec = dec_hasher.finish();
// Hash value of decimal 3.14159 is 2566941990314602357
// The hash of the floating-point number 3.14159 is 2566941990314602357
let str = "Hello 算法";
let mut str_hasher = DefaultHasher::new();
str.hash(&mut str_hasher);
let hash_str = str_hasher.finish();
// Hash value of string "Hello 算法" is 16092673739211250988
// The hash of the string “Hello 算法” is 16092673739211250988
let arr = (&12836, &"小哈");
let mut tup_hasher = DefaultHasher::new();
arr.hash(&mut tup_hasher);
let hash_tup = tup_hasher.finish();
// Hash value of tuple (12836, "小哈") is 1885128010422702749
// The hash of the tuple (12836, "小哈") is 1885128010422702749
let node = ListNode::new(42);
let mut hasher = DefaultHasher::new();
node.borrow().val.hash(&mut hasher);
let hash = hasher.finish();
// Hash value of ListNode object RefCell { value: ListNode { val: 42, next: None } } is 15387811073369036852
// The hash of the node object RefCell { value: ListNode { val: 42, next: None } } is 15387811073369036852
```
=== "C"
```c title="built_in_hash.c"
// C does not provide built-in hash code functions
// C provides no built-in hash-code function
```
=== "Kotlin"
@@ -348,27 +348,27 @@ We know that hash table keys can be integers, floating-point numbers, strings, a
```kotlin title="built_in_hash.kt"
val num = 3
val hashNum = num.hashCode()
// Hash value of integer 3 is 3
// The hash of the integer 3 is 3
val bol = true
val hashBol = bol.hashCode()
// Hash value of boolean true is 1231
// The hash of the Boolean true is 1231
val dec = 3.14159
val hashDec = dec.hashCode()
// Hash value of decimal 3.14159 is -1340954729
// The hash of the floating-point number 3.14159 is -1340954729
val str = "Hello 算法"
val hashStr = str.hashCode()
// Hash value of string "Hello 算法" is -727081396
// The hash of the string “Hello 算法” is -727081396
val arr = arrayOf<Any>(12836, "小哈")
val hashTup = arr.hashCode()
// Hash value of array [12836, 小哈] is 189568618
// The hash of the array [12836, 小哈] is 189568618
val obj = ListNode(0)
val hashObj = obj.hashCode()
// Hash value of ListNode object utils.ListNode@1d81eb93 is 495053715
// The hash of the node object utils.ListNode@1d81eb93 is 495053715
```
=== "Ruby"
@@ -376,35 +376,35 @@ We know that hash table keys can be integers, floating-point numbers, strings, a
```ruby title="built_in_hash.rb"
num = 3
hash_num = num.hash
# Hash value of integer 3 is -4385856518450339636
# The hash of the integer 3 is -4385856518450339636
bol = true
hash_bol = bol.hash
# Hash value of boolean true is -1617938112149317027
# The hash of the Boolean true is -1617938112149317027
dec = 3.14159
hash_dec = dec.hash
# Hash value of decimal 3.14159 is -1479186995943067893
# The hash of the floating-point number 3.14159 is -1479186995943067893
str = "Hello 算法"
hash_str = str.hash
# Hash value of string "Hello 算法" is -4075943250025831763
# The hash of the string “Hello 算法” is -4075943250025831763
tup = [12836, '小哈']
hash_tup = tup.hash
# Hash value of tuple (12836, '小哈') is 1999544809202288822
# The hash of the tuple (12836, '小哈') is 1999544809202288822
obj = ListNode.new(0)
hash_obj = obj.hash
# Hash value of ListNode object #<ListNode:0x000078133140ab70> is 4302940560806366381
# The hash of the node object #<ListNode:0x000078133140ab70> is 4302940560806366381
```
??? pythontutor "Visualized Execution"
??? pythontutor "Visualize execution"
https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%E5%B8%83%E5%B0%94%E9%87%8F%20True%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%E5%AD%97%E7%AC%A6%E4%B8%B2%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836,%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%E5%85%83%E7%BB%84%20%2812836,%20'%E5%B0%8F%E5%93%88'%29%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%AF%B9%E8%B1%A1%20%3CListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked-list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20next%20node%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20integer%203%20is%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20Boolean%20True%20is%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20floating-point%20number%203.14159%20is%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20string%20%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%20is%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20tuple%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20is%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20node%20object%20%3CListNode%20object%20at%200x1058fd810%3E%20is%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
In many programming languages, **only immutable objects can serve as the `key` in a hash table**. If we use a list (dynamic array) as a `key`, when the contents of the list change, its hash value also changes, and we would no longer be able to find the original `value` in the hash table.
In many programming languages, **only immutable objects can serve as hash-table keys**. If a list, a dynamic array, were used as a key, changing its contents would change its hash, making the original value impossible to retrieve from the table.
Although the member variables of a custom object (such as a linked list node) are mutable, it is hashable. **This is because the hash value of an object is usually generated based on its memory address**, and even if the contents of the object change, the memory address remains the same, so the hash value remains unchanged.
Custom objects, such as linked-list nodes, can be hashable even though their member variables are mutable. **Their hash is usually based on their memory address**, which stays the same even when their contents change.
You might have noticed that the hash values output in different consoles are different. **This is because the Python interpreter adds a random salt to the string hash function each time it starts up**. This approach effectively prevents HashDoS attacks and enhances the security of the hash algorithm.
You may notice different hash values when running the program in different consoles. **Each time the Python interpreter starts, it adds a random salt to its string hash function**. This helps prevent HashDoS attacks and improves security.