mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-28 23:34:43 +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:
48
ko/codes/python/chapter_greedy/coin_change_greedy.py
Normal file
48
ko/codes/python/chapter_greedy/coin_change_greedy.py
Normal file
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
File: coin_change_greedy.py
|
||||
Created Time: 2023-07-18
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def coin_change_greedy(coins: list[int], amt: int) -> int:
|
||||
"""동전 교환: 탐욕"""
|
||||
# coins 리스트가 정렬되어 있다고 가정한다
|
||||
i = len(coins) - 1
|
||||
count = 0
|
||||
# 남은 금액이 없을 때까지 탐욕적 선택을 반복한다
|
||||
while amt > 0:
|
||||
# 남은 금액보다 작으면서 가장 가까운 금액의 동전을 찾는다
|
||||
while i > 0 and coins[i] > amt:
|
||||
i -= 1
|
||||
# coins[i]를 선택한다
|
||||
amt -= coins[i]
|
||||
count += 1
|
||||
# 가능한 방법을 찾지 못하면 -1을 반환한다
|
||||
return count if amt == 0 else -1
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
# 탐욕: 전역 최적해를 찾는 것이 보장된다
|
||||
coins = [1, 5, 10, 20, 50, 100]
|
||||
amt = 186
|
||||
res = coin_change_greedy(coins, amt)
|
||||
print(f"\ncoins = {coins}, amt = {amt}")
|
||||
print(f"목표 금액 {amt}에 필요한 최소 동전 개수는 {res}개이다")
|
||||
|
||||
# 탐욕: 전역 최적해를 찾는 것이 보장되지 않는다
|
||||
coins = [1, 20, 50]
|
||||
amt = 60
|
||||
res = coin_change_greedy(coins, amt)
|
||||
print(f"\ncoins = {coins}, amt = {amt}")
|
||||
print(f"목표 금액 {amt}에 필요한 최소 동전 개수는 {res}개이다")
|
||||
print(f"실제로 필요한 최소 개수는 3개이며, 20 + 20 + 20이다")
|
||||
|
||||
# 탐욕: 전역 최적해를 찾는 것이 보장되지 않는다
|
||||
coins = [1, 49, 50]
|
||||
amt = 98
|
||||
res = coin_change_greedy(coins, amt)
|
||||
print(f"\ncoins = {coins}, amt = {amt}")
|
||||
print(f"목표 금액 {amt}에 필요한 최소 동전 개수는 {res}개이다")
|
||||
print(f"실제로 필요한 최소 개수는 2개이며, 49 + 49이다")
|
||||
46
ko/codes/python/chapter_greedy/fractional_knapsack.py
Normal file
46
ko/codes/python/chapter_greedy/fractional_knapsack.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
File: fractional_knapsack.py
|
||||
Created Time: 2023-07-19
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
class Item:
|
||||
"""물건"""
|
||||
|
||||
def __init__(self, w: int, v: int):
|
||||
self.w = w # 물건의 무게
|
||||
self.v = v # 물건의 가치
|
||||
|
||||
|
||||
def fractional_knapsack(wgt: list[int], val: list[int], cap: int) -> int:
|
||||
"""분할 가능한 배낭: 탐욕"""
|
||||
# 무게와 가치 두 속성을 갖는 물건의 리스트를 생성한다
|
||||
items = [Item(w, v) for w, v in zip(wgt, val)]
|
||||
# 단위 가치 item.v / item.w를 기준으로 내림차순 정렬한다
|
||||
items.sort(key=lambda item: item.v / item.w, reverse=True)
|
||||
# 탐욕적 선택을 반복한다
|
||||
res = 0
|
||||
for item in items:
|
||||
if item.w <= cap:
|
||||
# 남은 용량이 충분하면 현재 물건을 통째로 배낭에 넣는다
|
||||
res += item.v
|
||||
cap -= item.w
|
||||
else:
|
||||
# 남은 용량이 부족하면 현재 물건의 일부를 배낭에 넣는다
|
||||
res += (item.v / item.w) * cap
|
||||
# 남은 용량이 없으므로 반복문을 종료한다
|
||||
break
|
||||
return res
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
wgt = [10, 20, 30, 40, 50]
|
||||
val = [50, 120, 150, 210, 240]
|
||||
cap = 50
|
||||
n = len(wgt)
|
||||
|
||||
# 탐욕 알고리즘
|
||||
res = fractional_knapsack(wgt, val, cap)
|
||||
print(f"배낭 용량을 초과하지 않는 물건의 최대 가치는 {res}이다")
|
||||
33
ko/codes/python/chapter_greedy/max_capacity.py
Normal file
33
ko/codes/python/chapter_greedy/max_capacity.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""
|
||||
File: max_capacity.py
|
||||
Created Time: 2023-07-21
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
|
||||
def max_capacity(ht: list[int]) -> int:
|
||||
"""최대 용량: 탐욕"""
|
||||
# i와 j가 각각 배열의 양 끝을 가리키도록 초기화한다
|
||||
i, j = 0, len(ht) - 1
|
||||
# 최대 용량의 초깃값은 0이다
|
||||
res = 0
|
||||
# 두 칸막이가 만날 때까지 탐욕적 선택을 반복한다
|
||||
while i < j:
|
||||
# 최대 용량을 갱신한다
|
||||
cap = min(ht[i], ht[j]) * (j - i)
|
||||
res = max(res, cap)
|
||||
# 낮은 칸막이를 안쪽으로 이동한다
|
||||
if ht[i] < ht[j]:
|
||||
i += 1
|
||||
else:
|
||||
j -= 1
|
||||
return res
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
ht = [3, 8, 5, 2, 7, 7, 3, 4]
|
||||
|
||||
# 탐욕 알고리즘
|
||||
res = max_capacity(ht)
|
||||
print(f"최대 용량은 {res}이다")
|
||||
33
ko/codes/python/chapter_greedy/max_product_cutting.py
Normal file
33
ko/codes/python/chapter_greedy/max_product_cutting.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""
|
||||
File: max_product_cutting.py
|
||||
Created Time: 2023-07-21
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
|
||||
def max_product_cutting(n: int) -> int:
|
||||
"""분할 후의 최대 곱: 탐욕"""
|
||||
# n <= 3이면 반드시 1 하나가 나오도록 분할해야 한다
|
||||
if n <= 3:
|
||||
return 1 * (n - 1)
|
||||
# 탐욕적으로 3을 떼어 낸다. a는 3의 개수이고 b는 나머지이다
|
||||
a, b = n // 3, n % 3
|
||||
if b == 1:
|
||||
# 나머지가 1이면 1 * 3 한 쌍을 2 * 2로 바꾼다
|
||||
return int(math.pow(3, a - 1)) * 2 * 2
|
||||
if b == 2:
|
||||
# 나머지가 2이면 별도로 처리하지 않는다
|
||||
return int(math.pow(3, a)) * 2
|
||||
# 나머지가 0이면 별도로 처리하지 않는다
|
||||
return int(math.pow(3, a))
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
n = 58
|
||||
|
||||
# 탐욕 알고리즘
|
||||
res = max_product_cutting(n)
|
||||
print(f"분할 후의 최대 곱은 {res}이다")
|
||||
Reference in New Issue
Block a user