Compsci 101, Fall 2014, Lab 4

The lab

In this lab you will:

Getting Credit for Lab 4

To get credit for this lab, you will need to enter your names and netids, and the answers to several questions on an online form.

Complete this form for credit for lab 4

(the same questions are accessible here as well).

Part 1: String and List 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

For each of the following questions, keep in mind that the variable in the question could represent a string or a list.

Answer these questions on the online form.
  1. What do you think the name of the string method is that returns the lower case version of a string? (see the String methods above and generalize).

  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? (Provide a specific example of when it's true and try to generalize)

  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? (Provide a specific example of when it's true and try to generalize)

  9. Explain when the value of st[0:2]*2 in st is True? (Provide a specific example of when it's true and try to generalize)

  10. When is the value of lst.count(lst[0]) the same as the value of len(lst) for a list lst? (Provide a specific example of when it's true and try to generalize)


Part 2: Reasoning about Conditionals

  1. In the following three examples, a higher fee is suppose to be assigned to a higher speed. For each of the following three choices, decide if the higher fee is assigned to the higher speed and if not explain why. For example, if the speed is 85, is the fee assigned always 60?

    
    # Example A    
        speed = 85
        fee = 0
        if speed > 35: 
            fee = 20
        if speed > 50: 
            fee = 40
        if speed > 75: 
            fee = 60
        print fee
        
    # Example B    
        speed = 85
        fee = 0
        if speed > 75: 
            fee = 60
        if speed > 50: 
            fee = 40
        if speed > 35: 
            fee = 20
        print fee    
        
    
    # Example C
        speed = 85
        if 35 < speed and speed <= 50: 
            fee = 20
        if 50 < speed and speed <= 75: 
            fee = 40
        if 75 < speed: 
            fee = 60
        print fee
    
  2. To which of the following is this expression equivalent:

    not ((x > y) and (y <= 3))
    1. (x > y) and (y <= 3)
    2. (x > y) or (y <= 3)
    3. (x < y) or (y >= 3)
    4. (x <= y) or (y > 3)
    5. (x <= y) and (y > 3)
  3. A year is a leap year when it has 366 days instead of 365 days. In the international Gregorian calendar a year is a leap year according to the following, correct but perhaps poorly worded, rules as obtained from http://www.timeanddate.com/date/leapyear.html
    1. Every year divisible by 4 is a leap year
    2. But every year divisible by 100 is NOT a leap year
    3. Unless the year is also divisible by 400, then it is still a leap year

    This means 1800, 1900, and 2100 are not leap years but 2000 and 2004 are leap years.

    Which of the following implementations of a method is_leap returns true if year is a leap year and false otherwise. For each one list whether or not it is correct. If a method is not correct, provide a value for year for which it returns the wrong value.

    def is_leap1 (year):
      if year % 400 == 0: return True
      if year % 100 == 0: return False
      if year %   4 == 0: return True
      return False
    
    
    def is_leap2 (year):
      return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
    
    
    def is_leap3 (year):
      if year % 100 == 0:                  return False
      if year % 400 == 0 or year % 4 == 0: return True 
      return False
          
  4. Complete the function all_same that returns true only if all three of the given values are the same. For example, a call to all_same with the values 3, 128, 255 should return False; while the values 128, 128, 128 should return True.
  5. def all_same (value1, value2, value3):
    
    
    
    

Part 3: APT and loop practice

You'll work on loops and strategies to solve one APT: ScoreItYahtzee which is part of the apt-3 group of APTs, so you can snarf them for testing. (note the filename for this APT is ScoreIt.py).

  1. What value should maxPoints return for the call maxPoints([2,2,4,5,4]) and why?

  2. The number of occurrences of 1 in a list toss is given by the expression toss.count(1) --- what expression gives the number of 2's that occur in the list toss?

  3. The code below sets variable best correctly to be the best score for a list toss if the only values in the list are 2 or 4. Explain in words why the second if CANNOT be an elif --- provide an example that would fail to set best correctly for a list of only 2's and 4's if an elif statement is used (explain your reasoning). best = 0 if 2*toss.count(2) > best: best = 2 * toss.count(2) if 4*toss.count(4) > best: best = 4 * toss.count(4)
  4. How do you generalize the code above by using a for loop and a loop variable roll ? for roll in [1,2,3,4,5,6]:

After answering the questions together, you can individually work on completing this APT.


Part 4: APT Silver Distance

Do this section if you have time, if not no worries...

Discuss strategies for solving the APT Silver Distance. Do not write code together, just discuss how one might go about solving this problem.

There is nothing for the online form for this part.