프로그래머스 - 모음사전

dobyming·2023년 2월 8일
0

문제 설명

사전에 알파벳 모음 'A', 'E', 'I', 'O', 'U'만을 사용하여 만들 수 있는, 길이 5 이하의 모든 단어가 수록되어 있습니다. 사전에서 첫 번째 단어는 "A"이고, 그다음은 "AA"이며, 마지막 단어는 "UUUUU"입니다.

단어 하나 word가 매개변수로 주어질 때, 이 단어가 사전에서 몇 번째 단어인지 return 하도록 solution 함수를 완성해주세요.

제한사항

  • word의 길이는 1 이상 5 이하입니다.
  • word는 알파벳 대문자 'A', 'E', 'I', 'O', 'U'로만 이루어져 있습니다.

입출력 예

wordresult
"AAAAE"6
"AAAE"10
"I"1563
"EIO"1189

내 코드

from itertools import product
def solution(word):
    answer = 0
    aeiou = "AEIOU"
    
    words = []
    for i in range(1,6):
        for t in product(list(aeiou),repeat = i):
            words.append(''.join(list(t)))
    words.sort()
    answer = words.index(word) + 1
    return answer   

아이디어

'중복해서 단어를 1글자부터 5글자까지 단어를 만들 수 있다' 에서 아이디어를 얻었다.

Python에서는 itertools 모듈에서 중복 순열과 중복 조합을 지원해준다. 대박

1. 중복 순열 : product

nπrnπr : 중복 가능한 n개에서 r개를 택하여 일렬로 나열하는 경우의 수.
nπrnπr = nrn^r

사용법

1) from itertools import product 를 import
2) product('배열이름', repeat = '중복 허용 개수')

from itertools import product

sets = [1,2,3]

#2개를 뽑아 일렬로 나열하는 경우의 수(단, 중복 허용)
data = product(sets, repeat = 2)

for i in data:
   print(i)

#print
(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)
(2, 3)
(3, 1)
(3, 2)
(3, 3)

2. 중복 조합 : combinations_with_replacement

nHrnHr : 중복 가능한 n개에서 순서를 생각하지 않고 r개를 택하는 경우의 수

사용법

1) from itertools import combinations_with_replacement 를 import
2) itertools.combinations_with_replacement('배열이름', '중복 허용 개수')

from itertools import combinations_with_replacement

sets = [1,2,3]

#2개를 뽑아 일렬로 나열하는 경우의 수(단, 중복 허용)
data = itertools.combinations_with_replacement(sets, 2)

for i in data:
   print(i)

#print
(A, A)
(A, B)
(A, C)
(B, B)
(B, C)
(C, C)

0개의 댓글