An Introduction to the Itertools Package
The package that allows us to solve combinatorial problems is called
the itertools module, which you can import with import itertools. (The itertools functions
are the real stars of the lecture!) For our purposes
1. print "[ ",
for col in xrange(cols): if (col > 0): print ",", # The next 2 lines print a[row][col] with the given fieldWidth format = "%" + str(fieldWidth) + "s" print format % str(a[row][col]), print "]", print "]"
# Let's give the new function a try!
1. the same row
a = myDeepCopy(a) # once again, meant to make each row distinct a[0][0] = 42 # so we hope this only
modifies first row print a [0, 0], [0, 0] # finally, prints [42, 0],
# what's going on with deepcopy? Answer: if the original list has alia
1. print "
b =", b c =", c
print "
# Now modify a[0][0] a[0][0] = 9 print "But after a[0][0] = 9" print " print " print " a =", a b =", b c =", c
limitations of copy.deepcopy of aliases a = [0]*2]*3 # makes 3 shallow copies of (aliases of) the same row a[
1. Nested Looping over 2d Lists
# Create an "arbitrary" 2d List a = [ [ 2, 3, 5] , [ 1, 4, 7 ] ] print "Before: a =", a
# Now find its dimensions rows = len(a) cols = len(a[0])
# And now loop over every element # Here, we'll add one to each element, # jus
1.1.
a[0][0]=42" print " a =", a
1.2.
Even Better: make2dList()
def make2dList(rows, cols): a=[] for row in xrange(rows): a += [0]*cols] return a
rows = 3 cols = 2 a = make2dList(rows, cols) print "This IS ok. print " a =", a At first:"
a[0][0] = 42 print
1. List Comprehensions 2. # Examples from http:/www.python.org/dev/peps/pep-0202/ 3. # Note: just because you can do some of these more exotic things, 4. # does not mean you necessarily should!
5. Clarity above all!
6. print [i for i in range(10)] 7. # pr