์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ๋ฅผ ์œ„ํ•œ ํŒŒ์ด์ฌ ๋ฌธ๋ฒ• - ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ

๋‚ด๊ฐ€ ํ—ท๊ฐˆ๋ฆฌ๊ฑฐ๋‚˜ ๋ชฐ๋ž๋˜ ๋ถ€๋ถ„๋งŒ ๊ธฐ๋กํ•œ๋‹ค โœ๏ธ

  • ํŒŒ์ด์ฌ ์ปค๋ฎค๋‹ˆํ‹ฐ์—์„œ ๋“ค์—ฌ์“ฐ๊ธฐ๋Š” 4๊ฐœ์˜ ๊ณต๋ฐฑ๋ฌธ์ž๊ฐ€ ์‚ฌ์‹ค์ƒ ํ‘œ์ค€์ด๋‹ค.

์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ๋ฅผ ์ค€๋น„ํ•˜๋ฉด ๋ฐ˜๋“œ์‹œ ์•Œ์•„์•ผ ํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ

1. ๋‚ด์žฅ ํ•จ์ˆ˜

  • print(), input()๊ณผ ๊ฐ™์€ ๊ธฐ๋ณธ ์ž…์ถœ๋ ฅ + sorted()์™€ ๊ฐ™์€ ์ •๋ ฌ ๊ธฐ๋Šฅ์„ ํฌํ•จํ•œ ๊ธฐ๋ณธ ๋‚ด์žฅ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
result = eval("(3+5)*7")
# 56

result2 = sorted([('ํ™๊ธธ๋™', 35), ('์ด์ˆœ์‹ ', 75), ('์•„๋ฌด๊ฐœ', 50)], key = lambda x: x[1], reverse = True)
# [('์ด์ˆœ์‹ ', 75), ('์•„๋ฌด๊ฐœ', 50), ('ํ™๊ธธ๋™', 35)]

2. itertools

  • ์ˆœ์—ด๊ณผ ์กฐํ•ฉ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ œ๊ณต
from itertools import permutations, combinations, product

data = ['A', 'B', 'C']
result1 = list(permutations(data, 3)) # ์ˆœ์—ด ๊ตฌํ•˜๊ธฐ
result2 = list(combinations(data, 2)) # ์กฐํ•ฉ ๊ตฌํ•˜๊ธฐ
result3 = list(product(data, repeat=2)) # ์ˆœ์—ด ๊ตฌํ•˜๊ธฐ (์ค‘๋ณต ํ—ˆ์šฉ)

3. heapq

  • ํž™ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ, ์šฐ์„ ์ˆœ์œ„ ํ ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
  • min heap์œผ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์Œ, ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ O(NlogN)
  • max heap์„ ํ•˜๋ ค๋ฉด ๋ถ€ํ˜ธ๋ฅผ ๋ฐ˜๋Œ€๋กœ ํ•œ๋‹ค!
import heapq

h = []
heapq.heappush(h, value) # ์›์†Œ ์‚ฝ์ž…
heapq.heappop(h) # ์›์†Œ ๊บผ๋‚ด๊ธฐ

4. bisect

  • ์ด์ง„ ํƒ์ƒ‰ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
  • bisect_left() bisect_right() ํ•จ์ˆ˜๊ฐ€ ๊ฐ€์žฅ ์ค‘์š”ํ•˜๊ฒŒ ์‚ฌ์šฉ๋จ -> O(logN)
  • bisect_left(a, x) : ์ •๋ ฌ๋œ ์ˆœ์„œ๋ฅผ ์œ ์ง€ํ•˜๋„๋ก ๋ฆฌ์ŠคํŠธ a์— ๋ฐ์ดํ„ฐ x๋ฅผ ์‚ฝ์ž…ํ•  ๊ฐ€์žฅ ์™ผ์ชฝ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ๋Š” ๋ฉ”์†Œ๋“œ
  • bisect_right(a, x) : ์ •๋ ฌ๋œ ์ˆœ์„œ๋ฅผ ์œ ์ง€ํ•˜๋„๋ก ๋ฆฌ์ŠคํŠธ a์— ๋ฐ์ดํ„ฐ x๋ฅผ ์‚ฝ์ž…ํ•  ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ๋Š” ๋ฉ”์†Œ๋“œ
from bisect import bisect_left, bisect_right

a = [1, 2, 4, 4, 8]
x = 4
print(bisect_left(a, x)) # 2
print(bisect_right(a, x)) # 4

5. collections

  • ๋ฑ, ์นด์šดํ„ฐ ๋“ฑ์˜ ์œ ์šฉํ•œ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
  • deque : ํ๋ฅผ ๊ตฌํ˜„ํ•  ๋•Œ ์‚ฌ์šฉ, ๋ฆฌ์ŠคํŠธ์™€ ๋‹ค๋ฅด๊ฒŒ ์ธ๋ฑ์‹ฑ์ด๋‚˜ ์Šฌ๋ผ์ด์‹ฑ์€ ๋ถˆ๊ฐ€๋Šฅ, ์Šคํƒ์ด๋‚˜ ํ์˜ ์ž๋ฃŒ๊ตฌ์กฐ ๋Œ€์šฉ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Œ, ๋งจ ์•ž์— ์›์†Œ๋ฅผ ์ถ”๊ฐ€ํ•˜๊ฑฐ๋‚˜ ์ œ๊ฑฐํ•  ๋•Œ ๋ฆฌ์ŠคํŠธ๋Š” O(N) ์ด์ง€๋งŒ ๋ฑ์€ O(1)
  • Counter : ๋“ฑ์žฅ ํšŸ์ˆ˜๋ฅผ ์„ธ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค.
from collections import deque, Counter

data = deque([2, 3, 4])
data.appendleft(1)
data.append(5)
print(list(data)) # [1, 2, 3, 4, 5]

counter = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
print(counter['blue']) # 3
print(dict(counter)) # {'red': 2. 'blue': 3, 'green': 1}

6. math

  • ํ•„์ˆ˜์ ์ธ ์ˆ˜ํ•™์  ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ex. ํŒฉํ† ๋ฆฌ์–ผ, ์ œ๊ณฑ๊ทผ, ์‚ผ๊ฐํ•จ์ˆ˜, ํŒŒ์ด ์ƒ์ˆ˜ ๋“ฑ
import math

print(math.factorial(5)) # 5! => 120
print(math.gcd(21, 14)) # 7

์ฐธ๊ณ ์ž๋ฃŒ : ์ด๊ฒƒ์ด ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ๋‹ค (๋‚˜๋™๋นˆ ์ €)