Coding/Basic Skills(Python)

[Programmers, Level 1] Babbling 옹알이(2)

xeohyuni 2023. 6. 25. 22:52

Description:

Meosseugi is taking care of his 11-month old nephew. The nephew can only make four sounds: "aya," "ye," "woo," and "ma," and he struggles to produce consecutive sounds. Given a string array called "babbling" as a parameter, please complete the solution function to return the number of words that Meosseugi's nephew can pronounce.

 

Restriction:

  • 1 ≤ Length of babbling ≤ 100
  • 1 ≤ Length of babbling[i] ≤ 30
  • The strings are composed only of lowercase alphabets.

Input/Output Example:

babbling result
["aya", "yee", "u", "maa"] 1
["ayaye", "uuu", "yeye", "yemawoo", "ayaayaa"] 2

 

Example Explanation:

Example #1:
In the array ["aya", "yee", "u", "maa"], the only pronunciation that can be made is "aya." Therefore, it should return 1.

Example #2:
In the array ["ayaye", "uuuma", "yeye", "yemawoo", "ayaayaa"], there are two pronunciations that can be made: "aya" + "ye" = "ayaye" and "ye" + "ma" + "woo" = "yemawoo." The pronunciation "yeye" cannot be made due to consecutive identical sounds. Therefore, it should return 2.

 

Code:

def solution(babbling):
    ans = 0
    talk = ["aya", "ye", "woo", "ma" ]
    for babb in babbling:
        for t in talk:
            if t*2 not in babb:
                babb = babb.replace(t,' ')
        if babb.replace(' ','') == '':
            ans += 1
    return ans

Discusssion:

The provided code is a function called solution that takes in an array called babbling as input. The function aims to count the number of words that Meosseugi's nephew can pronounce. The function initializes a variable ans to keep track of the count of pronounceable words. It also creates a list called talk containing the four possible sounds that the nephew can make: "aya", "ye", "woo", and "ma".

The code then iterates over each string, represented by the variable babb, in the babbling array. For each babb, it further iterates over each sound, represented by the variable t, in the talk list. Inside the nested loop, there is a condition that checks if the sound t repeated twice is not present in babb. If the condition is true, it means that the nephew cannot pronounce consecutive identical sounds. In such cases, the sound t is replaced with a space in babb. This step helps filter out any consecutive identical sounds in babb. After going through all the sounds in talk, the code checks if babb contains only spaces when all consecutive identical sounds have been replaced. If it does, it means that the nephew can pronounce the word, and the count ans is incremented by 1.

Finally, the function returns the count ans, which represents the number of pronounceable words in the babbling array.

 

Overall, it was important to understand the timing, how, what the for function deletes and also pay attention to when only spaces are left.