티스토리 뷰

Python에서는 itertools 패키지를 이용해 순열과 조합의 결과를 산출할 수 있습니다. 

https://docs.python.org/3/library/itertools.html

 

itertools — Functions creating iterators for efficient looping

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python. The module standardizes a core set...

docs.python.org

 

Ex) 길이가 4인 리스트로 순열, 조합, 중복순열, 중복조합 결과를 출력하기

1. 순열 : 순서를 정해서 나열시키기

itertools 패키지에 permutations 함수 활용, permutations(iterable, 뽑을 원소의 개수)

a = [1,2,3,4]

#순열 : 순서를 정해서 나열 
print('순열 결과 : ', list(permutations(a,2)))   #4개의 원소 중 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)]

 

2. 조합 : 순서에 상관없이 나열시키기

combinations 함수 활용, combinations(iterable, 뽑을 원소의 개수)

#조합 : 순서에 상관없이 나열
print('조합 결과 : ', list(combinations(a,2))  #5개의 원소 중 2개를 뽑기

#조합 결과 :  [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

 

3. 중복 순열 : 중복을 허용해서 순서를 정해서 나열

product 함수 활용, product(iterable, 반복 횟수)

#중복순열 : 중복을 허용해서 순서를 정해서 나열
print('중복순열 결과 : ', list(product(a, repeat=2)))

#중복순열 결과 :  [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), 
				#(3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]

 

4. 중복 조합 : 중복을 허용해서 순서에 상관없이 나열

combinations_with_replacement 함수 활용

#중복조합 : 중복을 허용해서 순서에 상관없이 나열
print('중복조합 결과 : ', list(combinations_with_replacement(a, 2)))

# 중복조합 결과 :  [(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), 
					#(3, 3), (3, 4), (4, 4)]

 

https://school.programmers.co.kr/learn/courses/30/lessons/120869

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

spell과 dic 리스트가 입력되면, spell에 담긴 글자가 한번 씩만 모두 사용한 단어가 dic에 있는지 검사하는 문제

 

Test Case 1) spell = ['p', 'o', 's'], dic = ['sod', 'eocd', 'qixm', 'adio', 'soo']

spell의 원소를 모두 한 번씩만 사용하여 만든 글자 중 어느것도 dic 리스트에 없으므로 answer = 2

 

Test Case 2) spell = ['z', 'd', 'x'], dic = ['def', 'dww', 'dzx', 'loveaw']

spell의 원소를 모두 한번씩만 사용하여 만든 글자 중 'dzx'가 dic 리스트에 있으므로 answer = 1

 

Solution)

spell의 원소로 만들 수 있는 글자의 경우의 수를 모두 뽑아서 dic 리스트와 비교하기

-> 만들 수 있는 글자의 경우의 수 : spell 길이만큼 뽑아서 순서가 있게 나열하기 => itertools의 permutations 활용

-> 각 글자를 join함수로 더한 값이 dic list에 있으면 answer = 1, 없으면 answer = 2

from itertools import permutations

def solution(spell, dic):
    answer = 2
    list1 = list(permutations(spell, len(spell)))
    for x in list1:
        text = ''
        for idx in range(len(x)):
            text += x[idx]
        if text in dic:
            answer = 1
    return answer
TAG more
글 보관함
최근에 올라온 글