English to Pig Latin Translator

Problem:

Your objective is to write a Python program that takes a single English word as input and converts it to Pig Latin. The translation rules are as follows.

  1. If a word has no letters, don’t translate it.
  2. Assume all words are lowercase and there are no punctuation marks.
  3. Separate each word into two parts. The first part is called the prefix and extends from the beginning of the word up to, but not including, the first vowel. (The letter ’y’ will be considered a consonant.) The rest of the word is called the stem.
  4. The Pig Latin text is formed by reversing the order of the prefix and stem and adding the letters “ay” to the end. For example, “sandwich” is composed of the prefix “s” and the stem “andwich” and would translate to “andwichsay.”
  5. If the word contains no consonants, let the prefix be empty and the word be the stem. The word ending should be “yay” instead of merely “ay.” For example, “i” would be “iyay”.
  6. Make sure to handle the consonant cluster “qu” properly. For example, the word “question” should be “estion-quay” in Pig Latin and not “uestion-qay”

One Possible Solution:

def word_index(x):
    """ Returns index in word where stem starts """
    counter = 0
    for i in x:
        counter += 1
        if (i == "a" or i == "e" or i == "i" or i == "o" \
           or i == "u") and counter != 1:
            return counter - 1
        else:
            pass
        if counter == len(x):
            return 10000

def reverse_word(x, y):
    """ Reverse prefix and stem of the word x """
    yy = x[:y]
    zz = x[y:]
   
    if (y == 10000) and ((yy != "a") and (yy != "e") and (yy != "i") and \
                         (yy != "o") and (yy != "u")):
        print "Pig Latin: ", x + 'ay'
        return
    elif x[:2] == "qu":
        yyy = x[:2]
        zzz = x[2:]
        xyz = zzz + yyy + 'ay'
        print "Pig Latin: ", xyz
        return
    elif ((yy == "a") or (yy == "e") or (yy == "i") or \
          (yy == "o") or (yy == "u")):
        y2 = yy + 'yay'
        print "Pig Latin: ", y2
        return
    else:
        yz = zz + yy + 'ay'
        print "Pig Latin: ", yz

def main():
    """ Main program """
    x = raw_input("English: ")
    y = word_index(x)
    yy = reverse_word(x, y)

if __name__ == '__main__':
    main()

Original Assignment

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s