백준 문제 풀이

python permutations combinations 파이썬 순열 조합 itertools 모듈 사용. 사용법 정리. 문제점과 한계. 그리고 해결책

hjp845 2020. 4. 22. 21:29
반응형

입력이 들어오는 방식은 두가지

1. 문자열

import itertools

a = '1234'

print(list(map(''.join, itertools.permutations(a))))

 

['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314', '2341', '2413', '2431', '3124', '3142', '3214', '3241', '3412', '3421', '4123', '4132', '4213', '4231', '4312', '4321']

2. 숫자 배열 (문자 배열은 그냥 map(str, a) 없이 해주면 됨)

import itertools

a = [1, 2, 3, 4]

print(list(itertools.permutations(a)))

print(list(map(''.join, itertools.permutations(map(str, a)))))

 

[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314', '2341', '2413', '2431', '3124', '3142', '3214', '3241', '3412', '3421', '4123', '4132', '4213', '4231', '4312', '4321']

 

뭐 좋다.

근데 문제점이 있다.

import itertools

a = '111'

print(list(map(''.join, itertools.permutations(a))))

 

['111', '111', '111', '111', '111', '111']

...? 우리는 이런 결과를 원하는가? 메모리, 시간 다 비효율적이다.

combinations 도 마찬가지

import itertools

a = '111'

print(list(map(''.join, itertools.combinations(a, 2))))

 

['11', '11', '11']

음.. 쉣..

이게 한계다. 

이 비효율은 직접 구현해서 해결해야한다..

처음 수를 딱 정해주고, 아래 글에서 next_permutation 을 계속 돌려서 경우의 수를 따져주면 된다.

https://hjp845.tistory.com/67

.

.

그리고 가끔 문제를 풀다가

5개의 자리에서 두개의 자리를 골라줘야 되는 조합문제가 있는데

나는 처음엔

00011 이렇게 정하고, 위 글에서 next_permutation 써서 경우의 수를 따져줬다.

그런데

그냥 01234 주고 combinations(a, 2) 돌리는게 더 간단하네.

import itertools

a = '01234'

print(list(map(''.join, itertools.combinations(a, 2))))
['01', '02', '03', '04', '12', '13', '14', '23', '24', '34']

ㅇㅁㅇ..

그럼 모두 화이팅해라

반응형