Home > database >  Pig Latin Rules with Vowels
Pig Latin Rules with Vowels

Time:10-19

so I'm trying to write a code that will check each word in a string if there is a vowel in the beginning. If there is a vowel (upper or lowercase) then it will return the word and "-way" appended. If it begins with a consonant, then it moves the first letter to the back and appends "-ay" Ex: anchor = anchor-way, computer = omputer-cay .This is what I have but it seems like it's returning all words with these conditions and it's not checking for vowels. What am I doing wrong?

def pig_latin(text):
    say = []
    vowel = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']

    words = text.split()
    for vowel in words:
        vowel = vowel[0:]   "-way"
    say.append(vowel)

        if vowel not in words:
            vowel = vowel[1:]   "-"   vowel[0]   "ay"
        say.append(vowel)

    return " ".join(say)

 if __name__ == '__main__':
     result = pig_latin("hi how are you")
     print(result)

CodePudding user response:

When you write for vowel in words:, you aren't checking for vowels in words or doing any comparison. The expression for i in iterable: is a loop that will one-at-a-time set (in this case) i to each item in the iterable. In your case, it is setting the variable vowels to the first, then second, then third, ... item in your list called words. That is, it is overwriting your vowel list you created.

Try something like this.

def pig_latin(text):
    say = []
    vowel = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']

    words = text.split()
    for word in words: # loop over each word in the list of words
        if word[0] in vowel: # compare the first letter of the word against the vowel list
            new_word = word   '-way'
        else:
            new_word = word[1:]   '-'   word[0]   'ay'
        say.append(new_word)

    return " ".join(say)

 if __name__ == '__main__':
     result = pig_latin("hi how are you")
     print(result)

CodePudding user response:

there are a few things that you can do.

  • use the lower() function.
  • do not confuse vowels for words.
  • use enumerate to edit the existing list at the correct index.

This is a working version:

def pig_latin(sentance: str):
    words = sentance.split()
    vowels = ['a','e','i','o','u']

    for i, word in enumerate(words):
        if word[0].lower() in vowels:
            words[i] = word   '-way'
        else:
            words[i] = word[1:]   '-'   word[0]   'ay'

    return words

r = pig_latin("hi how are you")
print(r)

returns

['i-hay', 'ow-hay', 'are-way', 'ou-yay']
  • Related