Home > Blockchain >  CodeWars kata Vowel One
CodeWars kata Vowel One

Time:11-05

The code doesn't seem to replace non-vowel characters in a string.

def vowel_one(s):
    not_vowel = '0'
    
    vowels = {'a':'1', 
              'e':'1', 
              'i':'1', 
              'o':'1', 
              'u':'1'}
    #dictionary with keys as vowels, and their values as 1
    s = s.lower() #changing list to lowercase
    vowelsList = list(s)
        
    for index, item in enumerate(vowelsList): #counter, instead of doing i =1, using enumerate
        for key, value in vowels.items():
            if item == key: #if character in string is equal to key in dictionary
                vowelsList[index] = value #at the indexes of such characters, replace them with dictionary key values
                if item != key and item != '1':
                    vowelsList[index] = not_vowel
        
    return ("".join(vowelsList)) #removes brackets and ','

For example the result for "vowelOne" should be: 01010101 Instead I get: v1w1l1n1 Why does the other if statement not work? I imagine that if item in the given list (vowelsList) is not equal to any of the keys in dictionary (vowels), then it should replace it with a '0'. If I don't nest the if statements, then I get only 0s returned.

Link to kata: https://www.codewars.com/kata/580751a40b5a777a200000a1/

CodePudding user response:

  1. You don't require a dictionary if all your values are 1.
  2. You don't require two for loops that would just increase the time complexity.
  3. You don't require to convert the string into a list.

Here's my code:

def vowel_one(s):
    vowels = ['a', 'e','i', 'o', 'u'] # simple list
    #dictionary with keys as vowels, and their values as 1
    s = s.lower() #changing list to lowercase
    for i in s: # Iterating through every value
        if i in vowels: # Check if sub-string in vowels
            s = s.replace(i, '1')
        else: # If not vowel replace with 0
            s = s.replace(i, '0')
    return s
print(vowel_one("vowelOne"))

Edit: If you want to omit spaces you could add an elif condition. Try:

def vowel_one(s):
    vowels = ['a', 'e','i', 'o', 'u'] # simple list
    #dictionary with keys as vowels, and their values as 1
    s = s.lower() #changing list to lowercase
    for i in s: # Iterating through every value
        if i in vowels: # Check if sub-string in vowels
            s = s.replace(i, '1')
        elif not i.isspace(): # If not vowel and space replace with 0
            s = s.replace(i, '0')
    return s
print(vowel_one("Mudith is my name"))
  • Related