Go to: LING 1330/2330 home page  

Exercise 2: Python Refresher Quiz, Pig Latin

How is your Python knowledge? Expert or beginner, we could all use a refresher now and then.
If you need pointers, visit my Python 3 Notes.
This exercise consists of quiz questions and a script writing problem. The quiz questions are automatically scored but the script portion will not.

PART 1: Quiz

  1. Below is a script with a while statement nested in another. Which values go in ① and ② so it produces the shown shell output when executed?
    x = 0
    while x <=  :
        x += 1
        y = 0
        while y <=  :
            y += 1
            print(x, y)
        ============================ RESTART: foo.py =================
        1 1
        1 2
        1 3
        2 1
        2 2
        2 3
        3 1
        3 2
        3 3
        4 1
        4 2
        4 3
        5 1
        5 2
        5 3

  2. What should go in the blank so that the shown output is produced?
    >>> for i in       ?       :  
    ...     print(i)
        here we go 
    1. 'here we go'
    2. 'here we go'.split()
    3. ['here', 'we', 'go']
    4. ['here we go']

  3. Below, we have a list of lists. What's the output?
    >>> li = [[3, 3.14, 256, 9.99], [98, 99, 100], [-5, -20]] 
    >>> li[2]
        [-5, -20] 
    >>> li[1][0]

  4. Below, we have a list of strings. What is the output?
    >>> subjects = ['anthropology', 'economics', 'linguistics', 'biology', 'computer science']
    >>> subjects[2]
    >>> subjects[2][3]

  5. What goes in ① below? Pick all that fit.
    >>> sent = ['It', 'was', 'a', 'dark', 'and', 'stormy', 'night'] 
    >>> sent[2]
    >>> sent[2:5]
        ['a', 'dark', 'and'] 
    >>> sent[3:]
        ['dark', 'and', 'stormy', 'night'] 
        ['It', 'was', 'a'] 
    1. sent[5]
    2. sent[4]
    3. sent[-3]
    4. sent[4:5]

  6. [CONTINUED] What goes in ② in the session above? Pick all that fit.
    1. sent[0:3]
    2. sent[:-4]
    3. sent[:2]
    4. sent[:3]

  7. The script below contains a user-defined function. Once you execute it, you can call the function with an argument, as shown. What is the printed output in the shell?
    def hasE(word):
        ecount = word.count('E') + word.count('e')
        if ecount == 0:
            print(word, 'does not have any e.')
            print(word, 'has an e.')
        ============================ RESTART: foo.py =================
    >>> hasE('HELLO')

  8. [CONTINUED] You execute the same function hasE() in a different way, like shown below. Then you probe the variable result. What are the outputs in ① and ②?
    >>> result = hasE('HELLO')
                   ...something happens...               
    >>> print(result)
    >>> type(result)

  9. Below is another user-defined function, this time a "returning" kind. For fun, you are feeding a returned output from the function right back into it. What's the output?
    >>> def ahoyfy(word):
    ...    "Returns a word with 'o' replaced by '-ahoy-'."
    ...    return word.replace('o', '-ahoy-')
    >>> ahoyfy('cola')
    >>> ahoyfy('sophomore')
    >>> ahoyfy(ahoyfy('Honolulu'))

  10. [CONTINUED] You execute the same function ahoyfy() in a different way, like shown below. Then you probe the variable result. What are the outputs in ① and ②?
    >>> result = ahoyfy('sophomore')
    >>> print(result)
    >>> type(result)

  11. Below, we have successfully added an item to a list. What is the command used?
    >>> li = ['penguin', 'fox', 'owl', 'panda']
    >>>                ??               
    >>> li
        ['penguin', 'fox', 'owl', 'panda', 'elephant']
    1. li.add('elephant')
    2. li.extend('elephant')
    3. li += 'elephant'
    4. li.append('elephant')

  12. Below, we are concatenating two lists. What is the command used?
    >>> foo1 = ['rose', 'lily', 'violet', 'tulip']
    >>> foo2 = ['spruce', 'pine', 'oak']
    >>>                ??               
        ['rose', 'lily', 'violet', 'tulip', 'spruce', 'pine', 'oak']
    1. foo1.add(foo2)
    2. foo1.extend(foo2)
    3. foo1 + foo2
    4. foo1.append(foo2)

  13. Below is a dictionary of English irregular plural nouns. What's the shell output?
    >>> plu = {'mouse':'mice', 'goose':'geese', 'child':'children', 'tooth':'teeth'}
    >>> plu['goose']
    >>> plu['children']
    1. 'children'
    2. 'child'
    3. Nothing: the shell quietly goes back to the prompt.
    4. KeyError: ...

  14. [CONTINUED] On the same dictionary plu, which of the following for loops produces the shown shell output? Pick all. (NOTE: your lines might be ordered differently -- dictionary keys do not have an inherent order.)
        one mouse two mice 
        one goose two geese 
        one child two children 
        one tooth two teeth 
    for k in plu:
        print('one', k, 'two', plu[k])
    for k in plu.keys():
        print('one', k, 'two', plu[k])
    for k in plu.values():
        print('one', k, 'two', plu[k])
    for (k, v) in plu.items():
        print('one', k, 'two', v)

  15. [CONTINUED] Again operating on the dictionary plu, how do you get the following, alphabetically sorted, output? (There are a couple short solutions to this. One is just 11 characters!)
    >>>                ??               
        ['child', 'goose', 'mouse', 'tooth'] 

  16. Compose a function called areAnagrams(word1, word2). It takes two arguments word1 and word2, and returns True/False on whether they are anagrams of each other. An anagram is a word formed by rearranging the letters of a different word. Examples: 'cat' and 'act', 'state' and 'taste'. When executed, it should work like this:
    >>> def areAnagrams(word1, word2):
    ...     "Tests whether word1 and word2 are anagrams of each other"
    ...                    ??               
    >>> areAnagrams('cat', 'panda')
    >>> areAnagrams('night', 'thing')
    The solution is very simple when using a right built-in function. To submit, copy-and-paste the function in its entirety (i.e. including the def ... line at the top). This question won't be auto-graded.

  17. You wonder what attributes and methods are available for your string-type variable myword, so you call the built-in function dir() on it. Among the output (first few lines omitted here), you are curious about the isupper method, so you decide to print out the help message using help(). How is the command formulated? Two correct answers.
    >>> myword = 'Hello'
    >>> dir(myword)
        [ ...  
        '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 
        'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 
        'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 
        'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 
        'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 
        'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
    >>>           ??          
        Help on built-in function isupper:
            S.isupper() -> bool
            Return True if all cased characters in S are uppercase and there is
            at least one cased character in S, False otherwise.
    >>> myword.isupper()
    1. help(isupper)
    2. help(myword.isupper)
    3. help(myword.isupper())
    4. help(str.isupper)
    5. help(str.isupper())

  18. Below, we want to affix '$' in front of the dollar amount before printing it out. What is the exact formulation of the print function that accomplishes this?
    >>> monthly = 7000
    >>> monthly * 12
    >>> print(               ??               )
        Homer makes $84000 a year.
    1. 'Homer makes', '$', monthly*12, 'a year.'
    2. 'Homer makes', '$'+(monthly*12), 'a year.'
    3. 'Homer makes', '$'+str(monthly*12), 'a year.'
    4. 'Homer makes', '$monthly*12', 'a year.'

  19. A set is an orderless collection of distinct objects. In Python, set as a data type is marked with curly braces {}. set() as a function turns any sequence-type object into a set. Which of the following evaluates to False?
    1. {'a', 'b', 'c'} == {'b', 'c', 'a'}
    2. set('hello') == set('helllooooooooo')
    3. len(set(['a', 'man', 'a', 'plan', 'a', 'canal'])) == 4
    4. {'a', 'b', 'c'} < {'b', 'c', 'a', 'a', 'a', 'b'}

  20. Install NLTK and NLTK data (instructions here), and upload a screenshot of your successful setup (like this one). If you run into trouble (many do), ask help on MS Teams.

PART 2: Pig Latin [10 points]

Pig Latin is a language game where each word is transformed as follows:
    desk     -->    eskday       (esk-d-ay)
    chair    -->    airchay      (air-ch-ay)
    school   -->    oolschay     (ool-sch-ay)
    egg      -->    eggway       (egg-way)

Basically, the onset of the initial syllable (which is the word-initial consonant or consonant cluster) is moved to the end of the string, and then 'ay' is suffixed. For words that begin with a vowel sound, 'way' is suffixed.

Your job is to finish this template script. When completed, the whole script, named pig_latin.py, works as a Pig Latin translator:

    ================== RESTART: pig_latin.py =============
    Welcome to Pig Latin translator.
    Give me a sentence: We love school.
    Your Pig Latin sentence is:
    "Eway ovelay oolschay."
    ================== RESTART: pig_latin.py =============
    Welcome to Pig Latin translator.
    Give me a sentence: Colorless green ideas sleep furiously.
    Your Pig Latin sentence is:
    "Olorlesscay eengray ideasway eepslay uriouslyfay."

The script operates on a few key functions. The pigLatinWord() function translates a single word into its Pig Latin counterpart, and it relies on two functions getInitialCs() and getTheRest(). It should work like this:

>>> pigLatinWord('desk')
>>> pigLatinWord('school')
>>> pigLatinWord('egg')
The pigLatinSent(), on the other hand, works on sentential input. Under the hood, it has to translate each word: it first tokenizes the sentence string into a list of words, then applies pigLatinWord() to each of them. It gathers up the translated words in a new list called tran, which it converts back into a string via .join() before returning. It also properly capitalizes the first letter of the sentence, and put a period at the end. (You may disregard all other punctuation.) It is currently set up to return the exact same string as the input; you should modify it so it works exactly like:
>>> pigLatinSent('We love school.')
    'Eway ovelay oolschay.'
>>> pigLatinSent('Linguistics is hard.')
    'Inguisticslay isway ardhay.'

When developing this script, start with getTheRest() and build up. You can/should directly execute individual functions in IDLE shell following an execution of the script. Note that the main routine ("Welcome to... Give me a sentence:...") is there merely as a user interface, and it's best to ignore it while you are actively implementing the functions. New programmers will be tempted to use it as a testing tool during development, but you should instead use the pigLatinSent() function for testing, which is much quicker. And finally: remember to CODE IN SHELL.