본문 바로가기

Python(알고리즘,문제풀이)/프로그래머스(입문100제)

코딩테스트입문 / 옹알이(1) (permutations함수)

728x90

📚문제

출처 : 프로그래머스 / 옹알이(1) (https://school.programmers.co.kr/learn/courses/30/lessons/120956)

 

📝풀이

from itertools import permutations
def solution(babbling):
    word = ['aya', 'ye', 'woo', 'ma']
    cnt = 0
    word_list =[]

    for i in range(1,len(word)+1):
        for j in permutations(word,i):
            word_list.append(''.join(j))
    
    for i in babbling:
        if i in word_list:
            cnt += 1
    return cnt

문제를 보고 생각했던 풀이는 

아기가 말할 수 있는 단어들 (word) 로 조합 가능한 모든 단어들을 

만든 후에 

babbling의 for문을 돌며 있는지 확인 후 

cnt 세기

 

모든 조합 가능한 단어들을 만들기 위해

from itertools import permutations
-----------------------------------
예시

iterable = ['a', 'b', 'c']
length = 2
permutations_list = list(permutations(iterable, length))

print(permutations_list)
-----------------------------------
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

itertools모듈의 permutations 함수를 사용

 

+ 모듈 import 하지 않고 푸는 코드 참고

def solution(babbling):
    answer = []
    count = 0
    for n in babbling:
        n = n.replace('aya' , '*')
        n = n.replace('ye', '*')
        n = n.replace('woo' , '*')
        n = n.replace('ma', '*')
        answer.append(str(set(n)))
        
    for a in answer:
        if "{'*'}"== a:
            count += 1
        else:
            continue
    return count

입력 받는 babbling에서 아기가 말할 수 있는 단어가 포함되어 있으면 '*'로 치환

그리고 별의 개수는 중요하지 않으므로 ( 'aya'나 'ayaye'나 모두 어차피 아기가 말할 수 있는 단어로 이루어져 있음)

set()하여 리스트에 추가

 

어떤 말인지가 중요하다기보다 

아기가 말할 수있는 단어로만 이루어져있는지가 중요하기 때문에 이렇게 풀 수 있는 것 같다

 

위 코드의 예시를 들면

babbling = ["ayaye", "uuuma", "ye", "yemawoo", "ayaa"]
["{'*'}", "{'u', '*'}", "{'*'}", "{'*'}", "{'a', '*'}"]

이렇게 나온다

 

이 때 {'*}로 이루어져 있는 문자열만 확인( 아기가 말할 수 있는 단어인가 )

그래서 답은 3으로 나오게 된다

728x90