Lab 2: Lists and Functions

Simple lists. Give the output of each print statement for the following programs and answer any question in comments. I highly recommend using the visualizer for these problems.

  1. X = [0, 5, "cat", 2]
    print(type(X))
    print(type(X[2]))
    print(X[2])
    print(type(X[2]))
    X[2] = X[3]
    print(X[2])
    Y = ["pepper", 2, 3, 4]
    X.append(Y)
    print(X[4])
    print(X[4][0])
    
  2. X = ["a", "b", "c", "d", "e", "f"]
    X.remove("d")
    print(X)
    print(X[1:2])
    print(X[:2])
    print(X[2:])
    X[1:2] = []   # how many elements are removed?
    print(X)
    print(len(X))
    #X.remove(0) - if uncommented, why would this line cause an error?
    
  3. X = [1, 3, 5, 7, 9]
    print(X)
    X.extend(X)
    print(X)
    X.reverse()
    print(X)
    X.sort()
    print(X)
    
  4. X = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    X[0:2] = []
    print(X)
    X[2:5] = [50]
    print(X)
    X[1:2] = [100, 101, 102, 103, 104]
    print(X)
    X[len(X):] = [1000, 1001, 1002]
    print(X)
    
  5. Describe what the code below does in plain English:
    X[len(X):] = X
    
  6. X = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    print(X[::2])
    print(X[0:5:2])
    print(X[0:6:2])
    X[::2] = [0, 0, 0, 0, 0, 0] 
    print(X)
    #X[::2] = [5, 5]    Why does this code cause an error? 
    
  7. student_grades = [["Sid", "Strickland", 82], ["Josh", "Hug", 77], ["Tim", "Faust", 91], ["Kitty", "Vember", 39]]
    print("Name: " + student_grades[3][0] + " " + student_grades[3][1])
    print("Grade: " + str(student_grades[3][2]))
    

Functions on lists. For each of the following programs, give the results of each print statement.

  1. def p1(some_list):
        for item in some_list:
            print(item)
    
    p1(["cat", "dog", "bear", "horse"])
    
  2. Note: This function, while performing precisely the same function as #1, is generally considered inferior style in Python.
    def p2(some_list):
        N = len(some_list)
        for index in range(N):
            print(some_list[index])
    
    p2(["cat", "dog", "bear", "horse"])
    
  3. def p3(some_list):
        sum = 0
        for item in some_list[1::2]:
            print item
    
    p3(["cat", "dog", "bear", "horse"])
    
  4. def p4(some_list):
        sum = 0
        for item in some_list[:1:-1]:
            print item
    
    p4(["cat", "dog", "bear", "horse"])
    
  5. def sos(numbers, indices):
        sum = 0
        for index in indices:
            numberAtIndex = numbers[index]
            numberAtIndexSquared = numberAtIndex ** 2
            sum = sum + numberAtIndexSquared
        return sum
    
    print(sos([2, 4, 6, 8, 10], [0, 3, 4]))
    

Coding Exercises

Important note: When using IDLE, make sure to save your code using a .py extension. Otherwise, your code will not be highlighted correctly.

  1. Write a function longer_list(L1, L2) that takes two lists as arguments and returns the longer list. If they are both of the same length, you may return either list.
    X = [5, 6, 7, 8]
    Y = [91, "whistle", "corbodrum", True, 99]
    print longer_list(X, Y)
    
    should yield
    [91, 'whistle', 'corbodrum', True, 99]
    
  2. Write a function longest_list(L) that takes a list of lists as an argument and returns the longest list. If more than one list has the same length, you may return any of these lists.
    L = [[2, 5, 7, 1, 3], [9, 1, 2], ["uuuu", 5, 9], [5]]
    print(longest_list(L))
    
    should yield
    [2, 5, 7, 1, 3]
    
  3. Write a function find_closest(L, X) that takes two arguments: You may assume the first is a list of integers, and the second is an integer. The function should return the integer in L that is closest to X.
    L = [9, 15, 21, 25, 31, 40, 52]
    print(find_closest(L, 8))
    print(find_closest(L, 26))
    print(find_closest(L, 40))
    print(find_closest(L, 382378))
    
    should yield
    9
    25
    40
    52
    
  4. Write a module called grading.py. It should contain three functions as described below. Every function takes a list of lists called grade_spreadsheet as an argument.

    mean_grade(grade_spreadsheet)  Returns the mean of all grades as a float.
    print_all_grades(grade_spreadsheet)  Prints the name and grade of every student.
    print_grades_above_mean(grade_spreadsheet)  Prints the name and grade of every student whose score is above the mean.

    You may assume that the list of lists called grade_spreadsheet that is given to you follows a very special format. Each list in the list of lists must contain exactly three entries. The first entry is the first name of the student; the second entry is the last name of the student; the final entry is the grade of the student. An example of a valid list is shown below:

    grade_spreadsheet = [["Sid", "S.", 91.0], 
                      ["Josh", "H.", 71.0], 
                      ["Tim", "F.", 79.0], 
                      ["Kitty", "V.", 94.0],
                      ["Audrey", "H.", 77.0],
                      ["Mike", "B.", 90.0],
                      ["J.","S.", 90.0],
                      ["Lauren","D.", 96.0],
                      ["Dave","T.", 89.0],
                      ["Lisa","Q.", 74.0],
                      ["Matt","G.", 94.0],
                      ["Cocoa","T.", 95.0]] 
    
    Example outputs for the list above:
    print(mean_grade(grade_spreadsheet))
    86.6666666667
    
    grading.print_grades_above_mean(grade_spreadsheet)
    Name: Sid S.
    Grade: 91.0
    Name: Kitty V.
    Grade: 94.0
    Name: Mike B.
    Grade: 90.0
    Name: J. S.
    Grade: 90.0
    Name: Lauren D.
    Grade: 96.0
    Name: Dave T.
    Grade: 89.0
    Name: Matt G.
    Grade: 94.0
    Name: Cocoa T.
    Grade: 95.0
    
    grading.print_all_grades(grade_spreadsheet)
    Name: Sid S.
    Grade: 91.0
    Name: Josh H.
    Grade: 71.0
    Name: Tim F.
    Grade: 79.0
    Name: Kitty V.
    Grade: 94.0
    Name: Audrey H.
    Grade: 77.0
    Name: Mike B.
    Grade: 90.0
    Name: J. S.
    Grade: 90.0
    Name: Lauren D.
    Grade: 96.0
    Name: Dave T.
    Grade: 89.0
    Name: Lisa Q.
    Grade: 74.0
    Name: Matt G.
    Grade: 94.0
    Name: Cocoa T.
    Grade: 95.0
    

    Next week, we'll discuss better ways to package information than the list of lists approach above. We'll also discuss ways to better format the text output.

  5. The Coupon Collector's Problem.

    The local fast food chain Krivoburgers is running a promotion. Every time you buy a drink, your cup has a peel-off sticker numbered between 0 and N-1. Once you've collected one of every coupon, you get a free meal. Your goal is to figure out how many drinks you need to purchase on average before you get your first free meal.

    Write a function drink_simulation(N) which takes an integer N as an argument and simulates the process of buying drinks until all numbers appear. Your function should return the number of drinks that were purchased before all numbers appeared. You can generate a random number between 0 and N using random.randint(0, N).

    For testing purposes, while developing your code, have your function print out every number generated and verify that the results seem reasonable for small N. When you feel reasonably comfortable tha your code is working, you should remove all print statements from your drink_simulation function. As an example:

    How many distinct coupons? 5
    2
    2
    2
    4
    1
    4
    0
    0
    4
    3
    Total drinks purchased: 9
    
    Above, we can see that the program output seems reasonable, as the program stops immediately after all coupons have been acquired at least once. Since our user probably doesn't want his screen filling up with bazillions of mysterious printed numbers, we should remove the print statement from drink_simulation before sending the code to the end user.