코딩 테스트/Level 2

위클리 챌린지 5주차

컴닥 2021. 9. 4. 11:09
반응형

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

 

코딩테스트 연습 - 5주차

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

programmers.co.kr

 

파이썬

itertools를 이용하면 쉽게 풀 수 있습니다. 

from itertools import product


def solution(word):
    return sorted(
        [''.join(each) 
         for i in range(1, 6) 
         for each in product('AEIOU', repeat=i)]
    ).index(word) + 1

 

조금 풀어쓰면 이렇게 됩니다. 

from itertools import product


def solution(word):
    words = []
    for i in range(1, 6):
        for each in product('AEIOU', repeat=i):
            words.append(''.join(each))
    words = sorted(words)
    return words.index(word) + 1

 


    product(*iterables, repeat=1) --> product object
    
    Cartesian product of input iterables.  Equivalent to nested for-loops.
    
    For example, product(A, B) returns the same as:  ((x,y) for x in A for y in B).
    The leftmost iterators are in the outermost for-loop, so the output tuples
    cycle in a manner similar to an odometer (with the rightmost element changing
    on every iteration).
    
    To compute the product of an iterable with itself, specify the number
    of repetitions with the optional repeat keyword argument. For example,
    product(A, repeat=4) means the same as product(A, A, A, A).
    
    product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)
    product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...

반응형