Compsci 101, Fall 2017, Lab 6

Lists Comprehensions, getting started with APT and Hangman

For this lab you must work with a partner that you have not previously submitted a lab with.

The lab

In this lab you will:

For Lab 6, snarf the code for assignment 5. You will start the assignment in this lab.

Getting Credit for Lab 6

To get credit for lab, you will need to do the following by Sunday night:


Note: AnagramFree is part of APT Problem set Five, so it is due when the APT set is due.

Part 1: List Comprehensions

A Python list comprehension allows you to create a list from another list/sequence. For example the list comprehensions below generate the output shown. Note that a list comprehension is a list defined by a for-loop inside square brackets, and that the loop iterates over some list, creating a new list in the process. In the examples below, the output of each print statement is shown in italics.

somelist =  [x*2 for x in range(0,10)]
print somelist
[0,2,4,6,8,10,12,14,16,18]



somelist = [s[0] for s in ['apple', 'termite', 'elephant']]
print somelist
['a','t','e']



somelist =  [n % 2 == 0 for n in [2,4,6,1,3,5,8]]
print somelist
[True,True,True,False,False,False,True]


somelist = [n for n in [2,4,6,1,3,5,8] if n % 2 == 0]
print somelist
[2,4,6,8]


Without using a computer, (so by thinking) show what each line below prints. Enter your answers in the online form.
  1. print [x**2 for x in range(1,10,2)]
    
  2. print [s[1] for s in ["big", "brown", "bare", "stem", "pea"]]
    
  3. print ['po'*i for i in range(0,5)]
    
  4. print [i*i for i in range(1,10) if i % 2 == 0]
    
  5. print sum([1 for p in [1,2,3,4,5,6,7,8]])
    
  6. print sum([1 for x in "ostentatiously" if "aeiou".find(x) > -1])
    

    Generate List Comprehensions

    In writing your own list comprehensions it often helps to write intermediate expressions before creating the final list. Recall that the first variable in a comprehension determines the type of elements stored in the list. General steps in creating a list comprehension:


  7. Using a list comprehension write one expression using the function sum that returns the sum of all the odd integers in a list of integers named nums -- so for [1,3,2,4,5] your expression should evaluate to 9 --- fill in the parentheses: sum(...).

  8. Using a list comprehension and the list functions sum and len write an expression that returns the average length of all the strings in a list of strings named strs. So you'll call two list functions: one with strs as an argument and one with a list comprehension using strs as an argument: combining in one expression sum(...) and len(...). For example, the average length of the strings in the list below is (3+3+4+5)/4 = 15/4 = 3.75
      strs = ["cat", "dog", "bear", "tiger"]
    

  9. Write a list comprehension that creates a list of indexes of those words in a list of strings named los that begin with the letter 't'. For example,

    los = ['the','turtle','was','a','tiny','green','troubled','animal']
    
    The list comprehension should create [0,1,4,6], and it should work even when the values in los change to other strings.


Part 2: AnagramFree

Read the AnagramFree APT -- this part of the lab suggests using the Python construct set to make solving the APT simpler.

In Python a set does not store duplicates, each value is only stored once. For example, the code below generates the output shown:

x = set([1,2,3,1,2,3,1,2,3,1,1,1]) print len(x), x Output is:
  3, set([1,2,3])
A set can be created from a list as shown, and elements can be added to the set using the set method .add, e.g., s = set() s.add("big") s.add("big") s.add("big") s.add("small") s.add("small") print len(s),s will generate
   2, set(['small','big'])

  1. Write an expression that determines the number of different strings in the list foods below, e.g., that sets diff to have the value 4, but will work even if the values in food change: foods = ["bagel", "bagel", "cheese", "bagel", "hummus" "onion", "bagel", "onion"] diff =
  2. For a string s, the value of sorted(s) is a sorted list of the individual characters in the string, e.g., sorted("apple") = ['a','e','l','p','p']

    What's the value of the list comprehension below (write it out) --- you should have a list of lists:

    [sorted(w) for w in ['cow', 'dog', 'ant', 'bat']]
  3. The string method join creates a string from a list of strings as shown below.

    method call result
    ''.join(["a", "r", "t"]) "art"
    ' '.join(["the","big", "dog", "runs"]) "the big dog runs"

    The string to the left of the dot '.' is inserted between each string in the list that's a parameter to the join method and one string is returned as shown --- the new string is formed by concatenation. In the first call above an empty string '' is inserted, in the second a space ' ' is inserted.

    Using sorted and join write a list comprehension to create in unique the sorted string version of each string in words, e.g., to create ["aet", "aet", "aet", "abt", "abt", "deo" "deo"] out of the list ["eat", "aet", "tea", "bat", "tab", "ode", "doe"]

    words = ["eat", "aet", "tea", "bat", "tab", "ode", "doe"] unique =
  4. Using the techniques from the previous problems try to write a one line version of getMaximumSubset for the AnagramFree APT. Use set, sorted, join and a list comprehension. If you can't do it one line, use more than one. def getMaximumSubset(words): return len( )

REMEMBER - If you want to use this APT as one of your required APTs you must submit it through ambient/eclipse.


Part 3: Starting Hangman

This part of the lab suggests some ways to do parts of the Hangman assignment including the second part.

For this part you will snarf assignment 5 and get started on it. Here is also the code for starting.

The program starts by reading in words from the file lowerwords.txt. Then the user is asked for how many letters there are in a word.

  1. The function getPossibleWords has as input the list of all the words from the file, and also the length of a word the user specified. Complete this function using a list comprehension to return a list of only those words of the specified length.

  2. Since you cannot modify a string, for the word to guess named wordToGuess we represent it as a list of characters in the variable guessList. That is, guessList is a list that represents how many letters of the secret word have been guessed. For example, suppose the secret word is "ukelele". Then guessList is initially ["_", "_", "_", "_", "_", "_", "_"].

    The function updateLetter is given wordToGuess, guessList and letter and updates guessList if letter is in wordToGuess.
    NOTE: updateLetter is a mutator function, it should not have a return statement, there is no return value, it just modifies the list guessList.

    Here is an example of using updateLetter.

    wordToGuess = "ukelele" guessList = guessStart(wordToGuess) updateLetter(guessList,wordToGuess,"x") # guessList is now ["_", "_", "_", "_", "_", "_", "_" ] updateLetter(guessList,wordToGuess,"k") # guessList is now ["_", "k", "_", "_", "_", "_", "_" ] updateLetter(guessList,wordToGuess,"l") # guessList is now ["_", "k", "_", "l", "_", "l", "_" ]

    Note how the function is called. Since there is no return value, there is no value to catch in a variable. The list guessList is modified after each call if there was a change.

    Complete the function for updateLetter.

    def updateLetter(guessList,wordToGuess, letter):
    
    
  3. Try running your program. You should be able to play a game, only the game doesn't stop unless you get all the letters.

    Modify the code so that if the user guesses a letter that's not in word, the program prints a message "that's a miss", and otherwise prints "you guessed a letter" Explain in words changes you had to make.

  4. Modify the function playGame so that when the user is done, the program prints how many misses were made before all the letters in the word are guessed. You'll need to create an int variable, initialize it, update it, and print it when the loop exits.

    Cut and paste the function playGame.

  5. (THIS LAST ONE IS OPTIONAL FOR LAB, and DOES NOT HAVE TO BE TURNED IN AS PART OF LAB - But note it may be helpful to do for the assignment)
    Suppose that instead of a word you want to guess a phrase --- like a movie title, such as "Gone Girl" or "Star Wars: The Force Awakens". In that case, you would want to ask for a title with a certain number of words to guess, such as guess a title with three words.

    Write the function getPossiblePhrases that is similar to getPossibleWords and has the input, wordlist, which is a list of strings of all movie titles, and length, which is a number. This function should return the list of titles that have length words.

    For example if length is 3, return a list of strings of titles that are exactly three words.

    You should use a list comprehension in writing this code.