Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Pig Latin in the Python Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Implement a program that translates from English to Pig Latin.

Pig Latin is a made-up children's language that's intended to be confusing. It obeys a few simple rules (below), but when it's spoken quickly it's really difficult for non-children (and non-native speakers) to understand.

  • Rule 1: If a word begins with a vowel sound, add an "ay" sound to the end of the word. Please note that "xr" and "yt" at the beginning of a word make vowel sounds (e.g. "xray" -> "xrayay", "yttria" -> "yttriaay").
  • Rule 2: If a word begins with a consonant sound, move it to the end of the word and then add an "ay" sound to the end of the word. Consonant sounds can be made up of multiple consonants, a.k.a. a consonant cluster (e.g. "chair" -> "airchay").
  • Rule 3: If a word starts with a consonant sound followed by "qu", move it to the end of the word, and then add an "ay" sound to the end of the word (e.g. "square" -> "aresquay").
  • Rule 4: If a word contains a "y" after a consonant cluster or as the second letter in a two letter word it makes a vowel sound (e.g. "rhythm" -> "ythmrhay", "my" -> "ymay").

There are a few more rules for edge cases, and there are regional variants too.

See http://en.wikipedia.org/wiki/Pig_latin for more details.

Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of raise Exception, you should write:

raise Exception("Meaningful message indicating the source of the error")

Running the tests

To run the tests, run the appropriate command below (why they are different):

  • Python 2.7: py.test pig_latin_test.py
  • Python 3.4+: pytest pig_latin_test.py

Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version): python -m pytest pig_latin_test.py

Common pytest options

  • -v : enable verbose output
  • -x : stop running tests on first failure
  • --ff : run failures from previous test before running other test cases

For other options, see python -m pytest -h

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/pig-latin directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see the help page.

Source

The Pig Latin exercise at Test First Teaching by Ultrasaurus https://github.com/ultrasaurus/test-first-teaching/blob/master/learn_ruby/pig_latin/

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

pig_latin_test.py

import unittest

from pig_latin import translate


# Tests adapted from `problem-specifications//canonical-data.json` @ v1.2.0

class PigLatinTest(unittest.TestCase):
    def test_word_beginning_with_a(self):
        self.assertEqual(translate("apple"), "appleay")

    def test_word_beginning_with_e(self):
        self.assertEqual(translate("ear"), "earay")

    def test_word_beginning_with_i(self):
        self.assertEqual(translate("igloo"), "iglooay")

    def test_word_beginning_with_o(self):
        self.assertEqual(translate("object"), "objectay")

    def test_word_beginning_with_u(self):
        self.assertEqual(translate("under"), "underay")

    def test_word_beginning_with_a_vowel_and_followed_by_a_qu(self):
        self.assertEqual(translate("equal"), "equalay")

    def test_word_beginning_with_p(self):
        self.assertEqual(translate("pig"), "igpay")

    def test_word_beginning_with_k(self):
        self.assertEqual(translate("koala"), "oalakay")

    def test_word_beginning_with_x(self):
        self.assertEqual(translate("xenon"), "enonxay")

    def test_word_beginning_with_q_without_a_following_u(self):
        self.assertEqual(translate("qat"), "atqay")

    def test_word_beginning_with_ch(self):
        self.assertEqual(translate("chair"), "airchay")

    def test_word_beginning_with_qu(self):
        self.assertEqual(translate("queen"), "eenquay")

    def test_word_beginning_with_qu_and_a_preceding_consonant(self):
        self.assertEqual(translate("square"), "aresquay")

    def test_word_beginning_with_th(self):
        self.assertEqual(translate("therapy"), "erapythay")

    def test_word_beginning_with_thr(self):
        self.assertEqual(translate("thrush"), "ushthray")

    def test_word_beginning_with_sch(self):
        self.assertEqual(translate("school"), "oolschay")

    def test_word_beginning_with_yt(self):
        self.assertEqual(translate("yttria"), "yttriaay")

    def test_word_beginning_with_xr(self):
        self.assertEqual(translate("xray"), "xrayay")

    def test_y_is_treated_like_a_consonant_at_the_beginning_of_a_word(self):
        self.assertEqual(translate("yellow"), "ellowyay")

    def test_y_is_treated_like_a_vowel_at_the_end_of_a_consonant_cluster(self):
        self.assertEqual(translate("rhythm"), "ythmrhay")

    def test_y_as_second_letter_in_two_letter_word(self):
        self.assertEqual(translate("my"), "ymay")

    def test_a_whole_phrase(self):
        self.assertEqual(translate("quick fast run"), "ickquay astfay unray")


if __name__ == '__main__':
    unittest.main()
import sets
import string


class PigLatinTranslator:

    alpha = sets.Set(string.ascii_lowercase)
    vowels = sets.Set(['a', 'e', 'i', 'o', 'u'])
    consonants = alpha - vowels

    @classmethod
    def translate_phrase(cls, phrase):
        return ' '.join([cls.translate(word) for word in phrase.split()])

    @classmethod
    def translate(cls, word):
        if (word[0] in cls.vowels or
           word.startswith('yt') or
           word.startswith('xr')):
            return word + 'ay'
        elif (word.startswith('squ') or
                word.startswith('sch') or
                word.startswith('thr')):
            return word[3:] + word[0:3] + 'ay'
        elif ((word[0] in cls.consonants and
                word[1] in cls.consonants) or
                word.startswith('qu')):
            return word[2:] + word[0:2] + 'ay'
        elif (word[0] in cls.consonants):
            return word[1:] + word[0] + 'ay'


def translate(phrase):
    print PigLatinTranslator.alpha
    print PigLatinTranslator.vowels
    print PigLatinTranslator.consonants
    return PigLatinTranslator.translate_phrase(phrase)

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other peopleโ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?