Format python codes with black. (#453)

This commit is contained in:
Yudong Jin
2023-04-09 05:05:35 +08:00
committed by GitHub
parent 1c8b7ef559
commit 5ddcb60825
45 changed files with 656 additions and 456 deletions

View File

@ -4,26 +4,30 @@ Created Time: 2022-12-14
Author: msk397 (machangxinq@gmail.com)
"""
class Entry:
""" 键值对 int->String """
"""键值对 int->String"""
def __init__(self, key: int, val: str):
self.key = key
self.val = val
class ArrayHashMap:
""" 基于数组简易实现的哈希表 """
"""基于数组简易实现的哈希表"""
def __init__(self):
""" 构造方法 """
"""构造方法"""
# 初始化数组,包含 100 个桶
self.buckets: list[Entry | None] = [None] * 100
def hash_func(self, key: int) -> int:
""" 哈希函数 """
"""哈希函数"""
index: int = key % 100
return index
def get(self, key: int) -> str:
""" 查询操作 """
"""查询操作"""
index: int = self.hash_func(key)
pair: Entry = self.buckets[index]
if pair is None:
@ -31,19 +35,19 @@ class ArrayHashMap:
return pair.val
def put(self, key: int, val: str) -> None:
""" 添加操作 """
"""添加操作"""
pair = Entry(key, val)
index: int = self.hash_func(key)
self.buckets[index] = pair
def remove(self, key: int) -> None:
""" 删除操作 """
"""删除操作"""
index: int = self.hash_func(key)
# 置为 None ,代表删除
self.buckets[index] = None
def entry_set(self) -> list[Entry]:
""" 获取所有键值对 """
"""获取所有键值对"""
result: list[Entry] = []
for pair in self.buckets:
if pair is not None:
@ -51,7 +55,7 @@ class ArrayHashMap:
return result
def key_set(self) -> list[int]:
""" 获取所有键 """
"""获取所有键"""
result: list[int] = []
for pair in self.buckets:
if pair is not None:
@ -59,7 +63,7 @@ class ArrayHashMap:
return result
def value_set(self) -> list[str]:
""" 获取所有值 """
"""获取所有值"""
result: list[str] = []
for pair in self.buckets:
if pair is not None:
@ -67,7 +71,7 @@ class ArrayHashMap:
return result
def print(self) -> None:
""" 打印哈希表 """
"""打印哈希表"""
for pair in self.buckets:
if pair is not None:
print(pair.key, "->", pair.val)
@ -75,10 +79,10 @@ class ArrayHashMap:
""" Driver Code """
if __name__ == "__main__":
""" 初始化哈希表 """
# 初始化哈希表
mapp = ArrayHashMap()
""" 添加操作 """
# 添加操作
# 在哈希表中添加键值对 (key, value)
mapp.put(12836, "小哈")
mapp.put(15937, "小啰")
@ -88,18 +92,18 @@ if __name__ == "__main__":
print("\n添加完成后,哈希表为\nKey -> Value")
mapp.print()
""" 查询操作 """
# 查询操作
# 向哈希表输入键 key ,得到值 value
name = mapp.get(15937)
print("\n输入学号 15937 ,查询到姓名 " + name)
""" 删除操作 """
# 删除操作
# 在哈希表中删除键值对 (key, value)
mapp.remove(10583)
print("\n删除 10583 后,哈希表为\nKey -> Value")
mapp.print()
""" 遍历哈希表 """
# 遍历哈希表
print("\n遍历键值对 Key->Value")
for pair in mapp.entry_set():
print(pair.key, "->", pair.val)