CS150 - Fall 2012 - Class 14

  • exercise

  • admin
       - Behind the scenes tour of campus infrastructure tomorrow
          - 3pm at Warner Hemicycle
       - grading
          - Percentage breakdown on the course web page under "administrative"
          - Can do no worse than standard grade breakdown, eg. (>= 94 A, 90-93.9 A-, ...)
          - I *could* also shift grades slightly up if I felt like the exams, etc. were too hard, making all grades slightly better
             - right now, though the course seem roughly on track

  • you can only put immutable objects in a set
       - any guesses as to why?
          - objects are kept track of based on their contents
          - if their contents change, there is no easy way to let the set know this
       - what can/can't we store in a set?
          - can store:
             - ints
             - floats
             - strings
             - bools
          - can't store
             - lists
             - sets

  • tuples
       - there are occasions when we want to have a list of things, but it's immutable
          - for example, if we want to keep track of a list of things in a set
       - a "tuple" is an immutable list
       - tuples can be created as literals using parenthesis (instead of square braces)
          >>> my_tuple = (1, 2, 3, 4)
          >>> my_tuple
          (1, 2, 3, 4)
          >>> another_tuple = ("a", "b", "c", "d")
          >>> another_tuple
          ('a', 'b', 'c', 'd')

          - notice that when they print out they also show using parenthesis
       - tuples are sequential and have many of the similar behaviors as lists
          >>> my_tuple[0]
          1
          >>> my_tuple[3]
          4
          >>> for i in range(len(my_tuple)):
          ...    print my_tuple[i]
          ...
          1
          2
          3
          4
          >>> my_tuple[1:3]
          (2, 3)
       - tuples are immutable!
          >>> my_tuple[0] = 1
          Traceback (most recent call last):
           File "<string>", line 1, in <fragment>
          TypeError: 'tuple' object does not support item assignment
          >>> my_tuple.append(1)
          Traceback (most recent call last):
           File "<string>", line 1, in <fragment>
          AttributeError: 'tuple' object has no attribute 'append'
       
       - what about?
          >>> my_tuple = another_tuple
          >>> my_tuple
          ('a', 'b', 'c', 'd')
          >>> another_tuple
          ('a', 'b', 'c', 'd')
          
          - this is perfectly legal. We're not mutating a tuple, just reassigning our variable

  • generating histograms
       - we'd like to write a function that generates a histogram based on some input data
       - what is a histogram?
          - shows the "distribution" of the data (i.e. where the values range)
          - often visualized as a bar chart
             - along the x axis are the values (or bins)
             - and the y axis shows the frequency of those values (or bins)
       - for example, run histogram.py code
          >>> data = [1, 1, 2, 3, 1, 5, 4 ,2, 1]
          >>> print_counts(get_counts(data))

          - we can use Excel again to visualize this as a histogram
       - how can we do this?
          - we could do this like we did in assignment 5, where we sort and then count
          - but there's an easier way...
       - do it on paper: [1, 2, 3, 2, 3, 2, 1, 1, 5, 4, 4, 5]
          - how did you do it?
             - kept a tally of the number
             - each time you saw a new number, added it to your list with a count of 1
             - if it was something you'd seen already, add another tally/count
          - key idea, keeping track of two things:
             - a key, which is the thing you're looking up
             - a value, which is associated with each key

  • dictionaries (aka maps)
       - store keys and an associated value
          - each key is associated with a value
          - lookup can be done based on the key
          - this is a very common phenomena in the real world. What are some examples?
             - social security number
                - key = social security number
                - value = name, address, etc
             - phone numbers in your phone (and phone directories in general)
                - key = name
                - value = phone number
             - websites
                - key = url
                - value = location of the computer that hosts this website
             - car license plates
                - key = license plate number
                - value = owner, type of car, ...
             - flight information
                - key = flight number
                - value = departure city, destination city, time, ...
       - like sets, dictionaries allow us to efficiently lookup (and update) keys in the dictionary
       - creating new dictionaries
          - dictionaries can be created using curly braces
             >>> d = {}
             >>> d
             {}
          - dictionaries function similarly to lists, except we can put things in ANY index and can use non-numerical indices
             >>> d[15] = 1
             >>> d
             {15: 1}
             
             - notice when a dictionary is printed out, we get the key AND the associated value

             >>> d[100] = 10
             >>> d
             {100: 10, 15: 1}
             >>> my_list = []
             >>> my_list[15] = 1
             Traceback (most recent call last):
              File "<string>", line 1, in <fragment>
             IndexError: list assignment index out of range

             - dictionaries ARE very different than lists....
          - we can also update the values already in a list
             >> d[15] = 2
             >>> d
             {100: 10, 15: 2}
             >>> d[100] += 1
             >>> d
             {100: 11, 15: 2}
          - keys in the dictionary can be ANY immutable object
             >>> d2 = {}
             >>> >>> d2["dave"] = 1
             >>> d2["anna"] = 1
             >>> d2["anna"] = 2
             >>> d2["seymore"] = 100
             >>> d2
             {'seymore': 100, 'dave': 1, 'anna': 2}
          - the values can be ANY object
             - >>> d3 = {}
             >>> d3["dave"] = set()
             >>> d3["anna"] = set()
             >>> d3
             {'dave': set([]), 'anna': set([])}
             >>> d3["dave"].add(1)
             >>> d3["dave"].add(40)
             >>> d3["anna"].add("abcd")
             >>> d3
             {'dave': set([40, 1]), 'anna': set(['abcd'])}
          - be careful to put the key in the set before trying to use it
             >>> d3["steve"]
             Traceback (most recent call last):
              File "<string>", line 1, in <fragment>
             KeyError: 'steve'
             >>> d3["steve"].add(1)
             Traceback (most recent call last):
              File "<string>", line 1, in <fragment>
             KeyError: 'steve'
          - how do you think we can create non-empty dictionaries from scratch?
             >>> another_dict = {"dave": 1, "anna":100, "seymore": 21}
             >>> another_dict
             {'seymore': 21, 'dave': 1, 'anna': 100}
          - what are some other methods you might want for dictionaries (things you might want to ask about them?
             - does it have a particular key?
             - how many key/value pairs are in the dictionary?
             - what are all of the values in the dictionary?
             - what are all of the keys in the dictionary?
             - remove all of the items in the dictionary?
          - dictionaries support most of the other things you'd expect them too that we've seen in other data structures
             >>> "seymore" in another_dict
             True
             >>> len(another_dict)
             3
          - dictionaries are a class of objects, just like everything else we've seen (called dict ... short for dictionary)
             >>> help(dict)
          - some of the more relevant methods:
             >>> d2
             {'seymore': 100, 'dave': 1, 'anna': 2}
             >>> d2.values()
             [100, 1, 2]
             >>> d2.keys()
             ['seymore', 'dave', 'anna']
             >>> d2.clear()
             >>> d2
             {}