PyClass

Today

The While Loop:

a = 10
while a > 1:
  print a
  a -=1

The forever loop, (bad but sometimes useful):

a = 10
while True:
  print a
  a -= 1
  if a > 1: break

break and continue

def find(l, val):
  for elem in l:
    if l == val:
      print "found it!"  
      break
    
def do_if(l, func, func2):
  for elem in l:
    if not func(elem): continue
    func2(elem)
  

Remember that functions can be passed around!

sum (v1)

def sum(l):
  total = 0
  for elem in l: total += elem
  return total
    

sum (v2: recursion preview)

  def sum(l):
    if len(l) == 0: return 0
    return l[0] + sum(l[1:])

range Revisited

The range function loads all its values into memory:
# okay
for i in range(1000):
  print i

# will crash or error, too much memory consumed
l = # a list of every book on amazon
for i in range(len(l)):
  print i
    

What is the size of an int?

In Python 2.6 and above:

>>> import sys
>>> sys.getsizeof(1)
24
    

Not guaranteed to be the same everywhere, just gives you an idea

>>> sys.getsizeof(range(1000))
8072
>>> sys.getsizeof(range(1000000000)) # WARNING: DO NOT RUN
# your computer is now a heater
    

Enter xrange !

Calculates the values when needed instead of loading them all into memory.

 
>>> sys.getsizeof(xrange(1000))
40
>>> sys.getsizeof(xrange(100000))
40
>>> sys.getsizeof(xrange(10000000000))
40
    

xrange returns an iterator. We will learn to make our own iterators in a future class.

Sets

 
>>> a = set()
>>> a.add(1)
>>> a.add(2)
>>> a.add(1)
>>> a
set([1, 2])
 
>>> b = set([1, 1, 1, 2, 3, 4, 5, 5])
>>> b
set([1, 2, 3, 4, 5])
    

Sets are like lists, but with only one copy of each value.

A Very Simple unique Function

 
def unique(l):
  return list(set(l))
    

union and intersection

Intersection (only elements common to both sets):

>>> a & b
set([1, 2])
    

Union (elements in either set):

>>> a | b
set([1, 2, 3, 4, 5])

More Sets

Difference:

>>> b - a
set([3, 4, 5])

Subset:

>>> a <= b
True
>>> b <= a
False
    

Dictionaries

Key/value pairs:

d = {}
d["a"] = 1
d["b"] = 2
  

Dictionaries vs Lists

More Dictionaries

Top 3 Beatles Albums:

# dict
d = {1 : "Sgt. Peppers", 2: "The White Album", 3: "Abbey Road"}
# list
l = ["Sgt. Peppers", "The White Album", "Abbey Road"]
  

Which is a better representation?

Top 3 Albums By Different Artists:

# dict
d = {"The Beatles" : {1 : "Sgt. Peppers", 2: "The White Album", 3: "Abbey Road"},
     "Radiohead" : {...},
     "The National" : {...}
     }
# list
l = [["The Beatles", [..]], ["Radiohead", [..]], ["The National", [..]]]
  

Getting Keys and Values

>>> d = {1 : "Sgt. Peppers", 2: "The White Album", 3: "Abbey Road"}
>>> d.keys()
[1, 2, 3]
>>> d.values()
['Sgt. Peppers', 'The White Album', 'Abbey Road']
>>> 
  

The switch Statement

# This prints 50
choice = 'ham';
print { 'pram': 40,
    'ham' : 50,   
    'spam': 30,   
    'eggs': 2 }[choice] 
  

Default Values For a Dictionary

import collections
a = collections.defaultdict(lambda: 4)
print a[5] # will print '4'
  

Dictionaries as Objects

def sum(l):
  total = 0
  for x in l: total += x
  return total

def length(l):
  if l == []: return 0
  return 1 + length(l[1:])

mylist = {"value" : [1, 2, 3, 4]}
mylist["sum"] = sum
mylist["length"] = length

print mylist["length"](mylist["value"])
  

Problems