Compsci 6/101, Spring 2011, Lab 4

Turn in this page for your group

There are three parts to this lab:

  1. Practicing with new and old vocabulary to solve APTs. and practicing with list comprehensions to learn a new and powerful way of using existing vocabulary.

  2. Thinking together about some APTs.

  3. Practicing with light-bot

Vocabulary

A method is a function invoked on an object. For example, the table below shows some string methods.

string methodpurpose
s.upper() returns string upper case version of string s
s.count(sub) returns int number of (non-overlapping) occurrences of sub in s
s.endswith(sub) returns boolean depending on whether s ends with sub
s.find(sub) returns int: first index at which sub occurs in s or -1 if no occurrences
s.split() returns list of s split on whitespace
s.split(sep) returns list of s split on sep, a delimiter
s.strip() returns copy of s withOUT leading and trailing whitespace

list method purpose
lst.count(elt) returns number of occurrences of elt in lst
lst.index(elt) returns first/least index at which elt occurs in lst, generates error if elt not in lst
lst.append(elt) append elt to end of lst, None returned

Functions are applied to objects. For example, len returns an int: the length of a string or list or other sequence/iterable. So len("apple") is 5 and len([1,2,3]) is 3.

Other functions for lists include: sum (returns total, an int, of elements in a list); max,min which return largest and smallest elements in a list; sorted which returns a sorted version of a list; reversed which returns a reversed version of a list.

For example:

function call result returned type returned
len([1,2,3,"apple"]) 4 int
max([5,4,1,2,9,3]) returns 9 same as list elements
max("ape", "bee", "zebra", "wildebeast"] "zebra" same as list elements
min([5,4,1,2,9,3]) returns 1 same as list elements
sorted([5,4,1,2,7]) [1,2,4,5,7] list
reversed([1,2,3,6]) [6,3,2,1] list

Vocabulary Questions

  1. What do you think the name of the string method is that returns the lower case version of a string?

  2. The function max returns the maximal value of a string as well as a list. What is max("science") and why?

  3. What is the value of reversed(sorted([5,4,1,2,8])) and why?

  4. What is the value of sorted(lst).index(min(lst)) for any list lst? Why? What's the value if min is replaced by max?

  5. Why is the value of str.endswith(str[-3:]) True?

  6. When is the value of st.upper().endswith(st) True?

  7. The in operator determines if its left operand occurs in its right operand and returns a boolean value. This means 'a' in 'stranger' evaluates to True. What is the value of 5 in [1,2,3,4]?

  8. Explain when the value of st[0:2] in st is False?

  9. Explain when the value of st[0:2]*2 in st is True?

  10. When is the value of lst.count(lst[0]) the same as the value of len(lst) for a list lst?

    Vocabulary: 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.
    print [x*2 for x in range(0,10)]
    [0,2,4,6,8,10,12,14,16,18]
    
    
    
    print [s[0] for s in ['apple', 'termite', 'elephant']]
    ['a','t','e']
    
    
    
    print [n % 2 == 0 for n in [2,4,6,1,3,5,8]]
    [True,True,True,False,False,False,True]
    
    
    print [n for n in [2,4,6,1,3,5,8] if n % 2 == 0]
    [2,4,6,8]
    
    
    
    Without typing on any computer, (so by thinking) show what each line below prints. Try to reason about the code shown. Write your answers on the turn in sheet for lab.
  11. print [x**2 for x in range(1,10,2)]
    
  12. print [s[1] for s in ["big", "brown", "bare", "stem", "pea"]]
    
  13. print ['po'*i for i in range(0,5)]
    
  14. print [i*i for i in range(1,10) if i % 2 == 0]
    
  15. print sum([1 for p in [1,2,3,4,5,6,7,8]])
    
  16. print sum([1 for x in "ostentatiously" if "aeiou".find(x) > -1])
    

    Generate List Comprehensions

  17. 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 num -- so for [1,3,2,4,5] your expression should evaluate 9 --- fill in the parentheses: sum(...).

  18. 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(...)

APT Questions

Some of these APTs can be solved using list comprehensions by transforming the data for the problem. Other APTs are probably better solved by modifying the data.

Bagels

Write your answers on the turn in sheet for lab.

This week you worked on the Bagels APT. Four student solutions are shown below, you'll be asked some vocabularly questions and some analysis questions about these solutions.

# solution A def bagelCount(orders): bagels = 0 for i in orders: if i < 12: bagels = bagels + i if i == 12: bagels = bagels + i + 1 if i > 12: bagels = bagels + i + (i/12) return bagel # solution B def bagelCount(orders): for i in range(0, len(orders)): if orders[i] >= 12: b = orders[i] / 12 orders[i] = orders[i] + b return sum(orders)
# solution C def bakers_dozen(menu): bakery = 0 for i in menu: if i >= 12: bakery += i/12 return bakery def bagelCount(orders): return sum(orders) + bakers_dozen(orders) #solution D def bagelCount(orders): t = sum(orders) for int in orders: if int == 60: t = 5 + t elif int >= 48: t = 4 + t elif int >= 36: t = 3 + t elif int >= 24: t = 2 + t elif int >= 12: t = 1 + t else: t = t return t

  1. Which solution uses indexes to reference the values in the list orders rather than accessing the values directly? How do you know?

  2. Which solution uses a helper function? What is the function's name?

  3. Which solution alters the values in the list passed to bagelCount?

  4. Which solution(s) would no longer work if the maximal value of a bagel order is changed from 60 to 100? Why?

  5. How could Solution A be modified so that the body of the for loop consists of one assignment statement to bagels -- i.e., so that one of the three assignment statements in the code is used and no others are used, and no if statments are used?

  6. Write a list comprehension that creates a new list using the values from orders so that the function bagelCount can be written as below, where you fill in the blank with an expression that uses variable b: def bagelCount(orders): return sum([ for b in orders])

ScoreIt/Yahtzee

Write your answers on the turn in sheet for lab.

First consider this APT: Yahtzee/Scoreit

  1. What should the function maxPoints return for the list [4,3,3,5,2]? Why?

  2. Write an expression using the list method count that evaluates to the number of occurrences of the value 5 in the list toss. How does the expression change to evaluate to the number of occurrences of the value 3? 6?

  3. Write a list comprehension that creates a list of six values: the number of occurrences of each of the values/die-rolls 1,2,3,4,5,6 in the list toss. For example, the list comprehension should create the list [0,1,2,0,2,0] for toss = [3,2,5,3,5].

    Think about how you are transforming a list of dice rolls to a list of the number of occurrences of each possible die-roll.

  4. Modify the list comprehension you wrote above so that it creates a list of the scores for each possible die-roll/value: 1,2,3,4,5,6. For example, for toss = [5,3,5,3,3] the list comprehension should create [0,0,9,0,10,0] (why?)

  5. Write the function maxPoints using only list comprehensions and list functions, e.g., using a transformative approach.

ClassScores

You'll answer some questions here for the APT ClassScores that will lead toward a transformational approach to solving the problem.

  1. Create a list comprehension that assigns to a variable occs (occurrences) values that represent the number of occurrences of each value 0,1,2,...,100 -- in that order-- in the list scores. The list created will have 101 values. You should use the expression range(0,101) and the list method count.

    For example, if scores = [2,2,2,1,100] the list comprehension should create occs = [0,1,3,0,0,...,0,1] (why?)

  2. Given the list from the previous problem how will you determine how many times the mode(s) occur? Use one of the list functions max, sum, or len and the variable occs --- store the maximal number of occurrences of the mode in a variable named mode.

  3. Write a list comprehension that creates a new list that will be the return value of findMode. This list should use for i in range(0,101) and an if statement that uses values of occs and the value you stored in mode?

Light-Bot

Challenge/if time: play levels of light-bot