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

[도서실습] 내일은 코딩테스트 with 파이썬(자료구조와 알고리즘의 기초부터 실전까지) - 문제 1) 옹알이(1)

yujinius 2024. 4. 29. 15:34

문제 링크: https://school.programmers.co.kr/tryouts/85889/challenges?language=python3

 

[도서실습] 내일은 코딩테스트 with 파이썬(자료구조와 알고리즘의 기초부터 실전까지)

문제 1) 옹알이(1)

접근 방법 

1. 조카가 말할 수 있는 발음으로 조카가 말할 수 있는 단어 사전 만들기

2. babbling 내의 단어들을 검사하면서 조카가 말할 수 있는 단어 사전에 포함되어 있는지 판별하여 개수 세기

import itertools

def solution(babbling):
    count = 0
    can_speak_words = ["aya", "ye", "woo", "ma"]
    # 말할 수 있는 단어는 최대 1번씩만 등장
    # 순열로 애기가 말할 수 있는 모든 단어 만들어두기 
    can_speak_sentence=[]
    for i in range(1, 5):
        can_speak_sentence += list(itertools.permutations(can_speak_words, i))
    
    #print(can_speak_sentence)
    # join으로 단어 조합 합쳐서 말할 수 있는 단어집 만들기
    combined_words = [''.join(word_tuple) for word_tuple in can_speak_sentence]
    #print(combined_words)
    
    # 애기가 말할 수 있는 단어집에 해당하는 것들 count해주기
    for babb in babbling:
        if babb in combined_words:
            count+=1
    
    
    return count

 

포인트

  • 말할 수 있는 단어 목록 'combined_words'를 만들기 위해서 itertools의 permutations로 순열을 구해줌
  • 구해진 순열 튜플들은 내부적으로 ('aya', 'ye') 이런식으로 구성되어 있는데 이를 ''.join()을 통해 'ayaye'로 합쳐줌
  • babbling에 있는 단어가 combined_words에 있는지 확인하여 count해줌

 

순열과 조합을 손쉽게 구할 수 있는 파이썬의 itertools에 대한 자세한 설명은 아래 포스트에서 참고하기

https://yujinius45.tistory.com/52

 

[Python] 파이썬 순열, 조합, 중복 순열, 중복 조합  itertools 함수 (permutations, combinations, product, combina

순열/조합/중복 순열/중복 조합이란? 순열 (nPr) 서로 다른 n개 중에 r개를 선택해 일렬로 나열하는 경우의 수 (순서 상관 O) 조합 (nCr) 서로 다른 n개 중에 r개를 순서 생각 안하고 선택하는 경우의

yujinius45.tistory.com