///
Search

์ˆœ์—ด/์กฐํ•ฉ - itertools ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์‚ฌ์šฉ

๋ถ„๋ฅ˜
๋ชจ๋“ˆ
์†์„ฑ
์ƒ์„ฑ์ผ
2022/01/27 20:21
์ตœ์ข… ์ˆ˜์ •
2022/01/27 21:19

์ˆœ์—ด

itertools.permutations(iterable,ย r=None)
์ฒซ ๋ฒˆ์งธ ์ธ์ž์—๋Š” iterable ๊ฐ์ฒด๊ฐ€ ์˜ค๊ณ , ๋‘ ๋ฒˆ์งธ ์ธ์ž r ์€ iterable ๊ฐ์ฒด ์ „์ฒด์—์„œ ์ˆœ์—ด์„ ๋ฝ‘๋Š” ๊ฐœ์ˆ˜(r๊ฐœ) ๋ฅผ ์ง€์ •ํ•œ๋‹ค. r ๊ฐ’์€ ๋””ํดํŠธ๋กœ None ์ด๋ฉฐ, ์ด ๋•Œ๋Š” iterable ๊ฐ์ฒด ์ „์ฒด์—์„œ ์ˆœ์—ด์„ ๋Œ๋ฆฐ๋‹ค.
์ˆœ์—ด ํŠœํ”Œ๋“ค์„ ๋ฆฌํ„ดํ•œ๋‹ค.
from itertools import permutations l = ['A', 'B', 'C'] for i in permutations(l): #r์„ ์ง€์ •ํ•˜์ง€ ์•Š๊ฑฐ๋‚˜ r=None์œผ๋กœ ํ•˜๋ฉด ์ตœ๋Œ€ ๊ธธ์ด์˜ ์ˆœ์—ด์ด ๋ฆฌํ„ด๋œ๋‹ค! print(i) # permutations() ์€ ํŠœํ”Œ๋“ค์„ ๋ฆฌํ„ดํ•œ๋‹ค. ''' ์ถœ๋ ฅ๊ฒฐ๊ณผ: ('A', 'B', 'C') ('A', 'C', 'B') ('B', 'A', 'C') ('B', 'C', 'A') ('C', 'A', 'B') ('C', 'B', 'A') '''
Python
๋ณต์‚ฌ
items = [1, 2, 3, 4] print(list(permutations(items, 2))) # [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
Python
๋ณต์‚ฌ

์กฐํ•ฉ

itertools.combinations(iterable,ย r)
์กฐํ•ฉ์—์„œ๋Š” ๋‘ ๋ฒˆ์งธ ์ธ์ž์ธ r ์ด ํ•„์ˆ˜๋‹ค.
from itertools import combinations l = [1,2,3] for i in combinations(l,2): print(i) ''' ์ถœ๋ ฅ ๊ฒฐ๊ณผ: (1, 2) (1, 3) (2, 3) '''
Python
๋ณต์‚ฌ
items = [1, 2, 3, 4] print(list(combinations(items, 2))) # [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
Python
๋ณต์‚ฌ

์ค‘๋ณต์ˆœ์—ด

itertools.product(*iterable,ย repeat=1)
์ˆœ์—ด, ์กฐํ•ฉ๊ณผ๋Š” ๋‹ค๋ฅด๊ฒŒ, ์—ฌ๋Ÿฌ iterable ์„ ์ธ์ž๋กœ ๋„ฃ์–ด์ค„ ์ˆ˜ ์žˆ๊ณ , iterable ๋“ค์— ์›์†Œ๋“ค์„ ํ•˜๋‚˜์”ฉ ๋นผ์™€์„œ ์ˆœ์„œ์Œ์„ ๊ตฌ์„ฑํ•œ๋‹ค. (์ค‘๋ณต์ˆœ์—ด)
from itertools import product l1 = ['A', 'B'] l2 = ['1', '2'] for i in product(l1,l2,repeat=1): #l1๊ณผ l2์—์„œ ๊ฐ๊ฐ 1๊ฐœ์”ฉ์„ ๋ฝ‘์€ ์ค‘๋ณต์ˆœ์—ด ์ˆœ์„œ์Œ print(i) ''' ์ถœ๋ ฅ๊ฒฐ๊ณผ: ('A', '1') ('A', '2') ('B', '1') ('B', '2') ''' for i in product(l1,repeat=3): #li์—์„œ ์ค‘๋ณต์„ ํ—ˆ์šฉํ•ด์„œ 3๊ฐœ์”ฉ์„ ๋ฝ‘์€ ์ˆœ์„œ์Œ # cf. product(l1,l1,l1,repeat=1)๊ณผ ๋™์ผํ•œ ์ถœ๋ ฅ print(i) ''' ์ถœ๋ ฅ๊ฒฐ๊ณผ: ('A', 'A', 'A') ('A', 'A', 'B') ('A', 'B', 'A') ('A', 'B', 'B') ('B', 'A', 'A') ('B', 'A', 'B') ('B', 'B', 'A') ('B', 'B', 'B') '''
Python
๋ณต์‚ฌ

์ค‘๋ณต์กฐํ•ฉ

combinations_with_replacement(iterable,r)
r ์€ ํ•„์ˆ˜์ธ์ž์ด๋‹ค.
iterable ์—์„œ ์›์†Œ ๊ฐœ์ˆ˜๊ฐ€ r ๊ฐœ์ธ ์ค‘๋ณต์กฐํ•ฉ ํŠœํ”Œ๋“ค์„ ๋ฆฌํ„ดํ•œ๋‹ค.
from itertools import combinations_with_replacement l = ['A', 'B', 'C'] for i in combinations_with_replacement(l,2): print(i) ''' ์ถœ๋ ฅ๊ฒฐ๊ณผ: ('A', 'A') ('A', 'B') ('A', 'C') ('B', 'B') ('B', 'C') ('C', 'C') '''
Python
๋ณต์‚ฌ