mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-04 12:12:45 +08:00
feat(ko): add the Korean online edition (#2006)
* feat(ko): add the complete Korean online edition * Use UTF-8 for Python CI output on Windows * Remove print-book promotion from the Korean site * fix(ko): preserve emphasis before Korean particles
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
"""
|
||||
File: array_hash_map.py
|
||||
Created Time: 2022-12-14
|
||||
Author: msk397 ([email protected])
|
||||
"""
|
||||
|
||||
|
||||
class Pair:
|
||||
"""키-값 쌍"""
|
||||
|
||||
def __init__(self, key: int, val: str):
|
||||
self.key = key
|
||||
self.val = val
|
||||
|
||||
|
||||
class ArrayHashMap:
|
||||
"""배열로 구현한 해시 테이블"""
|
||||
|
||||
def __init__(self):
|
||||
"""생성자"""
|
||||
# 버킷 100개를 포함하는 배열을 초기화한다
|
||||
self.buckets: list[Pair | None] = [None] * 100
|
||||
|
||||
def hash_func(self, key: int) -> int:
|
||||
"""해시 함수"""
|
||||
index = key % 100
|
||||
return index
|
||||
|
||||
def get(self, key: int) -> str | None:
|
||||
"""조회 연산"""
|
||||
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):
|
||||
"""추가 및 갱신 연산"""
|
||||
pair = Pair(key, val)
|
||||
index: int = self.hash_func(key)
|
||||
self.buckets[index] = pair
|
||||
|
||||
def remove(self, key: int):
|
||||
"""삭제 연산"""
|
||||
index: int = self.hash_func(key)
|
||||
# None으로 설정하여 삭제를 나타낸다
|
||||
self.buckets[index] = None
|
||||
|
||||
def entry_set(self) -> list[Pair]:
|
||||
"""모든 키-값 쌍 반환"""
|
||||
result: list[Pair] = []
|
||||
for pair in self.buckets:
|
||||
if pair is not None:
|
||||
result.append(pair)
|
||||
return result
|
||||
|
||||
def key_set(self) -> list[int]:
|
||||
"""모든 키 반환"""
|
||||
result = []
|
||||
for pair in self.buckets:
|
||||
if pair is not None:
|
||||
result.append(pair.key)
|
||||
return result
|
||||
|
||||
def value_set(self) -> list[str]:
|
||||
"""모든 값 반환"""
|
||||
result = []
|
||||
for pair in self.buckets:
|
||||
if pair is not None:
|
||||
result.append(pair.val)
|
||||
return result
|
||||
|
||||
def print(self):
|
||||
"""해시 테이블 출력"""
|
||||
for pair in self.buckets:
|
||||
if pair is not None:
|
||||
print(pair.key, "->", pair.val)
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
# 해시 테이블 초기화
|
||||
hmap = ArrayHashMap()
|
||||
|
||||
# 추가 연산
|
||||
# 해시 테이블에 (key, value) 키-값 쌍을 추가한다
|
||||
hmap.put(12836, "小哈")
|
||||
hmap.put(15937, "小啰")
|
||||
hmap.put(16750, "小算")
|
||||
hmap.put(13276, "小法")
|
||||
hmap.put(10583, "小鸭")
|
||||
print("\n추가를 마친 후의 해시 테이블\n키 -> 값")
|
||||
hmap.print()
|
||||
|
||||
# 조회 연산
|
||||
# 해시 테이블에 키 key를 입력하여 값 value를 얻는다
|
||||
name = hmap.get(15937)
|
||||
print("\n학번 15937을 입력하여 조회한 이름 " + name)
|
||||
|
||||
# 삭제 연산
|
||||
# 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다
|
||||
hmap.remove(10583)
|
||||
print("\n10583을 삭제한 후의 해시 테이블\n키 -> 값")
|
||||
hmap.print()
|
||||
|
||||
# 해시 테이블 순회
|
||||
print("\n키-값 쌍(키->값) 순회")
|
||||
for pair in hmap.entry_set():
|
||||
print(pair.key, "->", pair.val)
|
||||
|
||||
print("\n키 Key만 순회")
|
||||
for key in hmap.key_set():
|
||||
print(key)
|
||||
|
||||
print("\n값 Value만 순회")
|
||||
for val in hmap.value_set():
|
||||
print(val)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
File: built_in_hash.py
|
||||
Created Time: 2023-06-15
|
||||
Author: krahets ([email protected])
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import ListNode
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
num = 3
|
||||
hash_num = hash(num)
|
||||
print(f"정수 {num}의 해시값은 {hash_num}이다")
|
||||
|
||||
bol = True
|
||||
hash_bol = hash(bol)
|
||||
print(f"불리언 {bol}의 해시값은 {hash_bol}이다")
|
||||
|
||||
dec = 3.14159
|
||||
hash_dec = hash(dec)
|
||||
print(f"소수 {dec}의 해시값은 {hash_dec}이다")
|
||||
|
||||
str = "Hello 算法"
|
||||
hash_str = hash(str)
|
||||
print(f"문자열 {str}의 해시값은 {hash_str}이다")
|
||||
|
||||
tup = (12836, "小哈")
|
||||
hash_tup = hash(tup)
|
||||
print(f"튜플 {tup}의 해시값은 {hash(hash_tup)}이다")
|
||||
|
||||
obj = ListNode(0)
|
||||
hash_obj = hash(obj)
|
||||
print(f"노드 객체 {obj}의 해시값은 {hash_obj}이다")
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
File: hash_map.py
|
||||
Created Time: 2022-12-14
|
||||
Author: msk397 ([email protected])
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import print_dict
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
# 해시 테이블 초기화
|
||||
hmap = dict[int, str]()
|
||||
|
||||
# 추가 연산
|
||||
# 해시 테이블에 (key, value) 키-값 쌍을 추가한다
|
||||
hmap[12836] = "小哈"
|
||||
hmap[15937] = "小啰"
|
||||
hmap[16750] = "小算"
|
||||
hmap[13276] = "小法"
|
||||
hmap[10583] = "小鸭"
|
||||
print("\n추가를 마친 후의 해시 테이블\n키 -> 값")
|
||||
print_dict(hmap)
|
||||
|
||||
# 조회 연산
|
||||
# 해시 테이블에 키 key를 입력하여 값 value를 얻는다
|
||||
name: str = hmap[15937]
|
||||
print("\n학번 15937을 입력하여 조회한 이름 " + name)
|
||||
|
||||
# 삭제 연산
|
||||
# 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다
|
||||
hmap.pop(10583)
|
||||
print("\n10583을 삭제한 후의 해시 테이블\n키 -> 값")
|
||||
print_dict(hmap)
|
||||
|
||||
# 해시 테이블 순회
|
||||
print("\n키-값 쌍(키->값) 순회")
|
||||
for key, value in hmap.items():
|
||||
print(key, "->", value)
|
||||
|
||||
print("\n키 Key만 순회")
|
||||
for key in hmap.keys():
|
||||
print(key)
|
||||
|
||||
print("\n값 Value만 순회")
|
||||
for val in hmap.values():
|
||||
print(val)
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
File: hash_map_chaining.py
|
||||
Created Time: 2023-06-13
|
||||
Author: krahets ([email protected])
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from chapter_hashing.array_hash_map import Pair
|
||||
|
||||
|
||||
class HashMapChaining:
|
||||
"""체이닝 해시 테이블"""
|
||||
|
||||
def __init__(self):
|
||||
"""생성자"""
|
||||
self.size = 0 # 키-값 쌍 개수
|
||||
self.capacity = 4 # 해시 테이블 용량
|
||||
self.load_thres = 2.0 / 3.0 # 용량 확장을 수행하는 적재율 임계값
|
||||
self.extend_ratio = 2 # 용량 확장 배수
|
||||
self.buckets = [[] for _ in range(self.capacity)] # 버킷 배열
|
||||
|
||||
def hash_func(self, key: int) -> int:
|
||||
"""해시 함수"""
|
||||
return key % self.capacity
|
||||
|
||||
def load_factor(self) -> float:
|
||||
"""적재율"""
|
||||
return self.size / self.capacity
|
||||
|
||||
def get(self, key: int) -> str | None:
|
||||
"""조회 연산"""
|
||||
index = self.hash_func(key)
|
||||
bucket = self.buckets[index]
|
||||
# 버킷을 순회하다 key를 찾으면 해당 val을 반환한다
|
||||
for pair in bucket:
|
||||
if pair.key == key:
|
||||
return pair.val
|
||||
# key를 찾지 못하면 None을 반환한다
|
||||
return None
|
||||
|
||||
def put(self, key: int, val: str):
|
||||
"""추가 연산"""
|
||||
# 적재율이 임계값을 초과하면 용량을 확장한다
|
||||
if self.load_factor() > self.load_thres:
|
||||
self.extend()
|
||||
index = self.hash_func(key)
|
||||
bucket = self.buckets[index]
|
||||
# 버킷을 순회하다 지정한 key를 만나면 해당 val을 갱신하고 반환한다
|
||||
for pair in bucket:
|
||||
if pair.key == key:
|
||||
pair.val = val
|
||||
return
|
||||
# 해당 key가 없으면 키-값 쌍을 맨 뒤에 추가한다
|
||||
pair = Pair(key, val)
|
||||
bucket.append(pair)
|
||||
self.size += 1
|
||||
|
||||
def remove(self, key: int):
|
||||
"""삭제 연산"""
|
||||
index = self.hash_func(key)
|
||||
bucket = self.buckets[index]
|
||||
# 버킷을 순회하며 키-값 쌍을 삭제한다
|
||||
for pair in bucket:
|
||||
if pair.key == key:
|
||||
bucket.remove(pair)
|
||||
self.size -= 1
|
||||
break
|
||||
|
||||
def extend(self):
|
||||
"""해시 테이블 용량 확장"""
|
||||
# 원래 해시 테이블을 임시로 저장한다
|
||||
buckets = self.buckets
|
||||
# 용량을 확장한 새 해시 테이블을 초기화한다
|
||||
self.capacity *= self.extend_ratio
|
||||
self.buckets = [[] for _ in range(self.capacity)]
|
||||
self.size = 0
|
||||
# 원래 해시 테이블의 키-값 쌍을 새 해시 테이블로 옮긴다
|
||||
for bucket in buckets:
|
||||
for pair in bucket:
|
||||
self.put(pair.key, pair.val)
|
||||
|
||||
def print(self):
|
||||
"""해시 테이블 출력"""
|
||||
for bucket in self.buckets:
|
||||
res = []
|
||||
for pair in bucket:
|
||||
res.append(str(pair.key) + " -> " + pair.val)
|
||||
print(res)
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
# 해시 테이블 초기화
|
||||
hashmap = HashMapChaining()
|
||||
|
||||
# 추가 연산
|
||||
# 해시 테이블에 (key, value) 키-값 쌍을 추가한다
|
||||
hashmap.put(12836, "小哈")
|
||||
hashmap.put(15937, "小啰")
|
||||
hashmap.put(16750, "小算")
|
||||
hashmap.put(13276, "小法")
|
||||
hashmap.put(10583, "小鸭")
|
||||
print("\n추가를 마친 후의 해시 테이블\n[키1 -> 값1, 키2 -> 값2, ...]")
|
||||
hashmap.print()
|
||||
|
||||
# 조회 연산
|
||||
# 해시 테이블에 키 key를 입력하여 값 value를 얻는다
|
||||
name = hashmap.get(13276)
|
||||
print("\n학번 13276을 입력하여 조회한 이름 " + name)
|
||||
|
||||
# 삭제 연산
|
||||
# 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다
|
||||
hashmap.remove(12836)
|
||||
print("\n12836을 삭제한 후의 해시 테이블\n[키1 -> 값1, 키2 -> 값2, ...]")
|
||||
hashmap.print()
|
||||
@@ -0,0 +1,138 @@
|
||||
"""
|
||||
File: hash_map_open_addressing.py
|
||||
Created Time: 2023-06-13
|
||||
Author: krahets ([email protected])
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from chapter_hashing.array_hash_map import Pair
|
||||
|
||||
|
||||
class HashMapOpenAddressing:
|
||||
"""개방 주소법 해시 테이블"""
|
||||
|
||||
def __init__(self):
|
||||
"""생성자"""
|
||||
self.size = 0 # 키-값 쌍 개수
|
||||
self.capacity = 4 # 해시 테이블 용량
|
||||
self.load_thres = 2.0 / 3.0 # 용량 확장을 수행하는 적재율 임계값
|
||||
self.extend_ratio = 2 # 용량 확장 배수
|
||||
self.buckets: list[Pair | None] = [None] * self.capacity # 버킷 배열
|
||||
self.TOMBSTONE = Pair(-1, "-1") # 삭제 표시
|
||||
|
||||
def hash_func(self, key: int) -> int:
|
||||
"""해시 함수"""
|
||||
return key % self.capacity
|
||||
|
||||
def load_factor(self) -> float:
|
||||
"""적재율"""
|
||||
return self.size / self.capacity
|
||||
|
||||
def find_bucket(self, key: int) -> int:
|
||||
"""key에 해당하는 버킷 인덱스 탐색"""
|
||||
index = self.hash_func(key)
|
||||
first_tombstone = -1
|
||||
# 선형 탐사로 탐색하고, 빈 버킷을 만나면 반복문을 종료한다
|
||||
while self.buckets[index] is not None:
|
||||
# key를 만나면 해당 버킷 인덱스를 반환한다
|
||||
if self.buckets[index].key == key:
|
||||
# 이전에 삭제 표시를 만났으면 키-값 쌍을 그 인덱스로 옮긴다
|
||||
if first_tombstone != -1:
|
||||
self.buckets[first_tombstone] = self.buckets[index]
|
||||
self.buckets[index] = self.TOMBSTONE
|
||||
return first_tombstone # 옮긴 후의 버킷 인덱스를 반환한다
|
||||
return index # 버킷 인덱스를 반환한다
|
||||
# 처음 만난 삭제 표시를 기록한다
|
||||
if first_tombstone == -1 and self.buckets[index] is self.TOMBSTONE:
|
||||
first_tombstone = index
|
||||
# 버킷 인덱스를 계산하고, 끝을 넘어가면 처음으로 돌아온다
|
||||
index = (index + 1) % self.capacity
|
||||
# key가 없으면 추가할 위치의 인덱스를 반환한다
|
||||
return index if first_tombstone == -1 else first_tombstone
|
||||
|
||||
def get(self, key: int) -> str:
|
||||
"""조회 연산"""
|
||||
# key에 해당하는 버킷 인덱스 탐색
|
||||
index = self.find_bucket(key)
|
||||
# 키-값 쌍을 찾으면 해당 val을 반환한다
|
||||
if self.buckets[index] not in [None, self.TOMBSTONE]:
|
||||
return self.buckets[index].val
|
||||
# 키-값 쌍이 없으면 None을 반환한다
|
||||
return None
|
||||
|
||||
def put(self, key: int, val: str):
|
||||
"""추가 연산"""
|
||||
# 적재율이 임계값을 초과하면 용량을 확장한다
|
||||
if self.load_factor() > self.load_thres:
|
||||
self.extend()
|
||||
# key에 해당하는 버킷 인덱스 탐색
|
||||
index = self.find_bucket(key)
|
||||
# 키-값 쌍을 찾으면 val을 덮어쓰고 반환한다
|
||||
if self.buckets[index] not in [None, self.TOMBSTONE]:
|
||||
self.buckets[index].val = val
|
||||
return
|
||||
# 키-값 쌍이 없으면 해당 키-값 쌍을 추가한다
|
||||
self.buckets[index] = Pair(key, val)
|
||||
self.size += 1
|
||||
|
||||
def remove(self, key: int):
|
||||
"""삭제 연산"""
|
||||
# key에 해당하는 버킷 인덱스 탐색
|
||||
index = self.find_bucket(key)
|
||||
# 키-값 쌍을 찾으면 삭제 표시로 덮어쓴다
|
||||
if self.buckets[index] not in [None, self.TOMBSTONE]:
|
||||
self.buckets[index] = self.TOMBSTONE
|
||||
self.size -= 1
|
||||
|
||||
def extend(self):
|
||||
"""해시 테이블 용량 확장"""
|
||||
# 원래 해시 테이블을 임시로 저장한다
|
||||
buckets_tmp = self.buckets
|
||||
# 용량을 확장한 새 해시 테이블을 초기화한다
|
||||
self.capacity *= self.extend_ratio
|
||||
self.buckets = [None] * self.capacity
|
||||
self.size = 0
|
||||
# 원래 해시 테이블의 키-값 쌍을 새 해시 테이블로 옮긴다
|
||||
for pair in buckets_tmp:
|
||||
if pair not in [None, self.TOMBSTONE]:
|
||||
self.put(pair.key, pair.val)
|
||||
|
||||
def print(self):
|
||||
"""해시 테이블 출력"""
|
||||
for pair in self.buckets:
|
||||
if pair is None:
|
||||
print("None")
|
||||
elif pair is self.TOMBSTONE:
|
||||
print("TOMBSTONE")
|
||||
else:
|
||||
print(pair.key, "->", pair.val)
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
# 해시 테이블 초기화
|
||||
hashmap = HashMapOpenAddressing()
|
||||
|
||||
# 추가 연산
|
||||
# 해시 테이블에 키-값 쌍 (key, val)을 추가한다
|
||||
hashmap.put(12836, "小哈")
|
||||
hashmap.put(15937, "小啰")
|
||||
hashmap.put(16750, "小算")
|
||||
hashmap.put(13276, "小法")
|
||||
hashmap.put(10583, "小鸭")
|
||||
print("\n추가를 마친 후의 해시 테이블\n키 -> 값")
|
||||
hashmap.print()
|
||||
|
||||
# 조회 연산
|
||||
# 해시 테이블에 키 key를 입력하여 값 val을 얻는다
|
||||
name = hashmap.get(13276)
|
||||
print("\n학번 13276을 입력하여 조회한 이름 " + name)
|
||||
|
||||
# 삭제 연산
|
||||
# 해시 테이블에서 키-값 쌍 (key, val)을 삭제한다
|
||||
hashmap.remove(16750)
|
||||
print("\n16750을 삭제한 후의 해시 테이블\n키 -> 값")
|
||||
hashmap.print()
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
File: simple_hash.py
|
||||
Created Time: 2023-06-15
|
||||
Author: krahets ([email protected])
|
||||
"""
|
||||
|
||||
|
||||
def add_hash(key: str) -> int:
|
||||
"""덧셈 해시"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash += ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
def mul_hash(key: str) -> int:
|
||||
"""곱셈 해시"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash = 31 * hash + ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
def xor_hash(key: str) -> int:
|
||||
"""XOR 해시"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash ^= ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
def rot_hash(key: str) -> int:
|
||||
"""회전 해시"""
|
||||
hash = 0
|
||||
modulus = 1000000007
|
||||
for c in key:
|
||||
hash = (hash << 4) ^ (hash >> 28) ^ ord(c)
|
||||
return hash % modulus
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
key = "Hello 算法"
|
||||
|
||||
hash = add_hash(key)
|
||||
print(f"덧셈 해시값은 {hash}이다")
|
||||
|
||||
hash = mul_hash(key)
|
||||
print(f"곱셈 해시값은 {hash}이다")
|
||||
|
||||
hash = xor_hash(key)
|
||||
print(f"XOR 해시값은 {hash}이다")
|
||||
|
||||
hash = rot_hash(key)
|
||||
print(f"회전 해시값은 {hash}이다")
|
||||
Reference in New Issue
Block a user