Files
hello-algo/en/codes/python/chapter_searching/hashing_search.py
Yudong Jin 2778a6f9c7 Translate all code to English (#1836)
* Review the EN heading format.

* Fix pythontutor headings.

* Fix pythontutor headings.

* bug fixes

* Fix headings in **/summary.md

* Revisit the CN-to-EN translation for Python code using Claude-4.5

* Revisit the CN-to-EN translation for Java code using Claude-4.5

* Revisit the CN-to-EN translation for Cpp code using Claude-4.5.

* Fix the dictionary.

* Fix cpp code translation for the multipart strings.

* Translate Go code to English.

* Update workflows to test EN code.

* Add EN translation for C.

* Add EN translation for CSharp.

* Add EN translation for Swift.

* Trigger the CI check.

* Revert.

* Update en/hash_map.md

* Add the EN version of Dart code.

* Add the EN version of Kotlin code.

* Add missing code files.

* Add the EN version of JavaScript code.

* Add the EN version of TypeScript code.

* Fix the workflows.

* Add the EN version of Ruby code.

* Add the EN version of Rust code.

* Update the CI check for the English version  code.

* Update Python CI check.

* Fix cmakelists for en/C code.

* Fix Ruby comments
2025-12-31 07:44:52 +08:00

52 lines
1.5 KiB
Python

"""
File: hashing_search.py
Created Time: 2022-11-26
Author: timi (xisunyy@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from modules import ListNode, list_to_linked_list
def hashing_search_array(hmap: dict[int, int], target: int) -> int:
"""Hash search (array)"""
# Hash table's key: target element, value: index
# If this key does not exist in the hash table, return -1
return hmap.get(target, -1)
def hashing_search_linkedlist(
hmap: dict[int, ListNode], target: int
) -> ListNode | None:
"""Hash search (linked list)"""
# Hash table's key: target element, value: node object
# If this key does not exist in the hash table, return None
return hmap.get(target, None)
"""Driver Code"""
if __name__ == "__main__":
target = 3
# Hash search (array)
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
# Initialize hash table
map0 = dict[int, int]()
for i in range(len(nums)):
map0[nums[i]] = i # key: element, value: index
index: int = hashing_search_array(map0, target)
print("Index of target element 3 =", index)
# Hash search (linked list)
head: ListNode = list_to_linked_list(nums)
# Initialize hash table
map1 = dict[int, ListNode]()
while head:
map1[head.val] = head # key: node value, value: node
head = head.next
node: ListNode = hashing_search_linkedlist(map1, target)
print("The corresponding node object for target node value 3 is", node)