본문 바로가기
코딩테스트/프로그래머스

[프로그래머스] 모음 사전 | 파이썬

by 애플파ol 2025. 5. 26.

Solution:

from itertools import product, combinations
def solution(word):
    list_al=['A', 'E', 'I', 'O', 'U']
    all_al=[]
    for i in range(1,5+1):
        a=list(product(list_al,repeat=i))
        
        for k in a:
            new_1=''.join(k) 
            all_al.append(new_1)
    all_al.sort()
    for index, kk in enumerate(all_al):
        if word==kk:
            answer=index
            break
    return answer+1

 

좀더 깔끔한 풀이

from itertools import product, combinations
def solution(word):
    dictionary=['A','E','I','O','U']
    words=[]
    for i in range(1,5+1):
        temp=list(product(dictionary,repeat=i))
        for i in temp:
            temp_word=''.join(i)
            words.append(temp_word)
    words.sort()
    # print(words)
    
    return words.index(word)+1

 

 

Skills:

  1. 중복순열 공식 product(list, repeat=숫자)
  2. 다른 공식 permutations(순열), combinations(조합), combinations_with_replacement (중복조합)
  3. '구분자'.join(iterable 객체)
  4. 문자열로 변환 후 sort하면 왼쪽에서 우측으로 문자를 하나하나를 Ascii 기준으로 비교함.
    - (첫번째 문자들끼리 비교하고, 두번째 문자들끼리 비교로 나아감
    - ex) 'A', 'AA', 'B' // (65), (65, 65) , (66)