본문 바로가기

Algorithm

옹알이 (2) / 프로그래머스

 

첫 번째 시도

  • 옹알이를 한 단어를 split을 이용해서 또 리스트로 나누려고 함
  • 생각해보니 re.split()은 문자를 제거하고 남은 부분만 반환해서 결과가 이상함
  • 옹알이가 가능한 단어가 딱 한번만 수행할 수 있는 줄 알았음
import re
babbling = ["aya", "yee", "u", "maa"]
def solution(babbling):
    ans = 0
    for i in babbling:
        s = re.split(r"[a,y,w,m]", i)
        dic = {"a": ["aya", False], "y": ["ye", False], "w": ["woo", False], "m": ["ma", False]}
        cnt = 0
        for j in s:
            if j[0] == "a" and dic["a"][1] != True:
                if j == dic["a"][0]:
                    cnt = cnt + 1
                    dic["a"][1] == True
            if j[0] == "y" and dic["y"][1] != True:
                if j == dic["y"][0]:
                    cnt = cnt + 1
                    dic["y"][1] == True
            if j[0] == "w" and dic["w"][1] != True:
                if j == dic["w"][0]:
                    cnt = cnt + 1
                    dic["w"][1] == True
            if j[0] == "m" and dic["m"][1] != True:
                if j == dic["m"][0]:
                    cnt = cnt + 1
                    dic["m"][1] == True
        if cnt == len(s):
            ans = ans + 1


    return ans

print(solution(babbling))

 

 

정답

  • 옹알이가 가능한 단어가 딱 한번만 수행할 수 있는 줄 알았음 -> 그냥 연속해서만 안 하면 됨
    • if w * 2 not in i : 이런식으로 연속해서 두 번 나왔는지 체크 가능
    • i.strip() : 앞뒤로 공백을 제거하는 함수 -> 옹알이가 가능한 부분은 모두 공백으로 치환 후 strip()으로 변경
    • i = i.replace(w," ") -> i 내부의 w를 " " 으로 치환
  • 연속해서 옹알이를 하면 안된다는 경우를 이때 알음 (문제를 잘 읽자..)
def solution(babbling):
    ans = 0
    word = ["aya", "ye", "woo", "ma"]
    for i in babbling:
        for w in word:
            if w * 2 not in i: #연속해서 옹알이를 하지 않았다면
                i = i.replace(w," ")#공백으로 치환
        
        if i.strip() == "": #앞 뒤 공백을 모두 제거하고 아무것도 없다면
            ans = ans + 1 #조건 충족
        
    return ans