[프로그래머스/Lv2] 모음사전

2022. 11. 22. 12:14

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

코드

from itertools import product

def solution(word):
    alphabet_list = ['A', 'E', 'I', 'O', 'U']

    word_list = []
    for i in range(1, len(alphabet_list)+1):
        word_list += [''.join(tp) for tp in list(product(alphabet_list, repeat=i))]

    sorted_word_list = sorted(word_list)

    return sorted_word_list.index(word)+1

 

 

설명

가장 무식한 방법으로 문제를 풀었다.

AEIOU로 만들 수 있는 모든 경우의 단어를 리스트에 저장해서

그 리스트를 사전순으로 정렬한 뒤, 입력받은 word의 인덱스를 구해 그 값에서 1을 더한 값을 반환할 것이다.

 

alphabet_list = ['A', 'E', 'I', 'O', 'U']

문제에서 주어진 모음 리스트이다.

 

from itertools import product

word_list = []
for i in range(1, len(alphabet_list)+1):
    word_list += [''.join(tp) for tp in list(product(alphabet_list, repeat=i))]

itertools 라이브러리의 product를 사용해서 중복을 허용하는 순열을 만든다.

word_list는 만든 단어를 저장해둘 리스트이다.

1부터 모음의 개수까지 반복한다.

길이가 i인 중복 순열을 만들어 나온 튜플들을 문자열로 바꿔 word_list에 저장한다.

 

sorted_word_list = sorted(word_list)

word_list를 사전순으로 정렬한다.

 

return sorted_word_list.index(word)+1

sorted_word_list에서 입력받은 word의 인덱스를 찾아 +1한 값을 반환한다.

BELATED ARTICLES

more