코딩 테스트/프로그래머스

[Python] 프로그래머스 lv.2 모음사전

위시리 2025. 4. 17. 17:38

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

 

문제 분석

  • 사전에 모음만을 사용하여 만들 수 있는 길이 5이하의 모든 단어가 수록
  • 사전 첫번째 단어 : 'A' - 'AA'
  • 마지막 단어 : 'UUUUU'
  • 단어 한 개가 매개변수로 주어질 때, 이 단어가 사전의 몇 번째 단어인지 Return

 

풀이

  • 몇개의 알파벳을 사용할 것인지 : 조합 5Ci
  • 모든 경우를 사전순으로 만들고 (순서O, 중복O) :  중복순열 : product (repeat)

 

정답 코드

import itertools

def solution(word):
    answer = 0
    
    vowel = ['A', 'E', 'I', 'O', 'U']
    words = []
    for i in range(1,6):
        for alp in itertools.combinations(vowel, i):
            alp_li = list(alp)
            
            for w in itertools.product(alp_li, repeat =i) :
                w = ''.join(map(str, w))
                if w in words :
                    continue
                words.append(w)
                    
    words = sorted(words)
    
    for idx in range(len(words)):
        if words[idx] == word :
            answer = idx + 1
            break
            
    
    return answer