๋กœ์ผ“๐Ÿพ
article thumbnail

 

itertools๋Š” ํŒŒ์ด์ฌ์—์„œ ๋ฐ˜๋ณต๋˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ธฐ๋Šฅ์„ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ž…๋‹ˆ๋‹ค.

 

๊ทธ ์ค‘ ์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” 4๊ฐ€์ง€ ํด๋ž˜์Šค์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

์•Œ์•„๋ณด๊ธฐ ์ „ ๊ณตํ†ต์œผ๋กœ ์•Œ์•„๋‘˜ ๊ฒƒ์ด ์žˆ์Šต๋‹ˆ๋‹ค.

 

  • itertools๋Š” ํŒŒ์ด์ฌ ์™ธ์žฅ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ด๋ฏ€๋กœ import ์„ ์–ธ์„ ํ•ด์ฃผ์–ด์•ผํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ combinations ํด๋ž˜์Šค๊ฐ€ ํ•„์š”ํ•˜๋‹ค๋ฉด from itertools import combinations ๋กœ ์„ ์–ธํ•ด์ฃผ์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.
  • ํ•ญ์ƒ list() ๋ฅผ ํ•ด์ฃผ์–ด ๋ฆฌ์ŠคํŠธ ๊ฐ์ฒด๋กœ ๋ฐ›์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค.
  • combinations ์ฒ˜๋Ÿผ ๋’ค์— s ๊ฐ€ ๋ถ™์–ด์žˆ๋Š”์ง€ ํ™•์ธํ•ด์ฃผ์–ด์•ผํ•ฉ๋‹ˆ๋‹ค. product ๊ฒฝ์šฐ๋Š” s๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.
ํ•จ์ˆ˜ ์„ค๋ช… ์‚ฌ์šฉ๋ฒ•
permutations iterable ๊ฐ์ฒด์—์„œ r๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฝ‘์•„ ์ˆœ์„œ๋Œ€๋กœ ๋‚˜์—ดํ•ฉ๋‹ˆ๋‹ค. permutations(๋ฆฌ์ŠคํŠธ, r๊ฐœ)
combinations iterable ๊ฐ์ฒด์—์„œ r๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฝ‘์•„ ์ˆœ์„œ๋Š” ๊ณ ๋ คํ•˜์ง€ ์•Š๊ณ  ๋‚˜์—ดํ•ฉ๋‹ˆ๋‹ค. combinations(๋ฆฌ์ŠคํŠธ, r๊ฐœ)
product iterable ๊ฐ์ฒด์—์„œ r๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฝ‘์•„ ์ˆœ์„œ๋Œ€๋กœ ๋‚˜์—ดํ•˜๊ณ  ์ค‘๋ณต์„ ํ—ˆ์šฉํ•ฉ๋‹ˆ๋‹ค. product(๋ฆฌ์ŠคํŠธ, repeat =3๊ฐœ)
combinations_with_replacement iterable ๊ฐ์ฒด์—์„œ r๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฝ‘์•„ ์ˆœ์„œ๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š๊ณ  ์ค‘๋ณต์„ ํ—ˆ์šฉํ•œ ์ฑ„ ๋‚˜์—ดํ•ฉ๋‹ˆ๋‹ค. combinations_with_replacement(๋ฆฌ์ŠคํŠธ, r๊ฐœ)

 

from itertools import permutations
from itertools import combinations
from itertools import product
from itertools import combinations_with_replacement

data = ['A', 'B', 'C']

print(list(permutations(data, 3)))# 3๊ฐœ ๋ฝ‘์•„ ์ˆœ์„œ ๊ณ ๋ ค && ๋งŒ์•ฝ data ์ˆ˜๋ณด๋‹ค ๋‘๋ฒˆ์งธ ์ธ์ž๊ฐ€ ๋” ํฌ๋ฉด ๋นˆ ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜
#[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]

print(list(combinations(data, 2)))# 2๊ฐœ ๋ฝ‘์•„ ์ˆœ์„œ ๊ณ ๋ ค ์•ˆํ•จ
#[('A', 'B'), ('A', 'C'), ('B', 'C')]

print(list(product(data, repeat=3)))# 3๊ฐœ ๋ฝ‘์•„ ์ˆœ์„œ ๊ณ ๋ คํ•˜๊ณ  ์ค‘๋ณต ํ—ˆ์šฉ
#๋ฐ์ดํ„ฐ๊ฐ€ ๋งŽ์•„์„œ ์ง์ ‘ํ•ด๋ณด์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.

print(list(combinations_with_replacement(data, 3)))# 3๊ฐœ ๋ฝ‘์•„ ์ˆœ์„œ ๊ณ ๋ ค์•ˆํ•˜๊ณ  ์ค‘๋ณต ํ—ˆ์šฉ
#[('A', 'A', 'A'), ('A', 'A', 'B'), ('A', 'A', 'C'), ('A', 'B', 'B'), ('A', 'B', 'C'), ('A', 'C', 'C'), ('B', 'B', 'B'), ('B', 'B', 'C'), ('B', 'C', 'C'), ('C', 'C', 'C')]

 

 

 

profile on loading

Loading...