Compsci 06/101, Fall 2011, Lab 5

By entering your name/net-id below you indicate you are present for Lab 5 to answer these questions and that you were part of the process that resulted in answers being turned in.

Name: ______________    Net id: _____________ || Name: ______________    Net id: _____________

Name: ______________    Net id: _____________ || Name: ______________    Net id: _____________

List Comprehensions

Python has a language feature called a list comprehension that allows you to create a list from another list/sequence. For example the list comprehensions below generate the output shown.

Traditional for loop List Comprehension Resulting list
result = range(0, 10)
for i,x in enumerate(result):
   result[i] = x*2
[x*2 for x in range(0,10)] [0,2,4,6,8,10,12,14,16,18]
words = ['apple','termite','elephant']
result = []
for s in words:
   result.append(s[0])
[s[0] for s in ['apple','termite','elephant']] ['a','t','e']
numbers = [2,4,6,1,3,5,8]
result = []
for n in numbers:
   if n % 2 == 0:
       result.append(n)
[n for n in [2,4,6,1,3,5,8] if n % 2 == 0] [2,4,6,8]
numbers = [2,4,6,1,3,5,8]
result = numbers[:]    # copy list
for i,n in enumerate(result):
    result[i] = (n % 2 == 0)
[n % 2 == 0 for n in [2,4,6,1,3,5,8]] [True,True,True,False,False,False,True]

Without typing on any computer, (so by thinking) show the resulting list for each line below.

[x**2 for x in range(1,10,2)]



[s[1] for s in ["apple", "big", "brown", "bare", "stem", "pea"]]



['po'*i for i in range(0,5)]



[i*i for i in range(1,10) if i % 2 == 0]



[x for x in "ostentatiously" if "aeiou".find(x) > -1]



    

Part 0: Thinking About Code

  1. Purpose/use of rc:
    
    
    
    
    
    
    
    
        
  2. Purpose/use of counts:
    
    
    
    
    
    
    
    
    
    
    

Part I: Craps Odds

  1. What are probabilities of winning and losing in craps on the first roll?
  2. win (7 or 11) =
    
    
    
    lose (2, 3, or 12) =
    
    
    
  3. Write what you consider the important part of the code that calculates the probabilities.
  4. 
    
    
    
    
    
    
    
    
    
    
    
    
    

Part II: Poker Odds

What odds did you calculate for each of the following poker hands?

  1. Pair (over how many dealt hands)?
    
    
    
    

  2. Two Pair (code and probability)
    
    
    
    
    
    
    

  3. Three of a Kind (code and probability)
    
    
    
    
    
    
    
    

  4. Full House (code and probability)
    
    
    
    
    
    
    
    
  5. Challenge Flush (code and probability)
    
    
    
    
    
    
    
  6. Challenge Straight (code and probability)