1. Example Using Sets 2. def repeats(a): 3. 4. 5. 6. 7. 8. 9.
10. print repeats([2,5,3,4,6,4,2]) # prints [2,4] seen = set() seenAgain = set() for element in a: if (element in seen): seenAgain.add(element) seen.add(element) return sorted(seenAgain)
1. Set Operations
See tables here.
1. Operations on a set
len(s) s.copy() s.pop() s.clear()
Result cardinality of set s new set with a shallow copy of s remove and return an arbitrary element from s; raises KeyError if empty remove all elements
1. s = set([2,True,"yes"])
print s # prints set([True, 2, 'yes'])
2. Elements Must Be Immutable 3. a = ["lists", "are", "mutable"] 4. s = set([a]) 5. print s
6. # TypeError: unhashable type: 'list'
7. s1 = set(["sets", "are", "mutable", "too"]) 8. s2 = se
pointList =  y=0 for x in xrange(1,k+3): #we removed 0 as the first element to avoid a row swap, so this becomes k+3 instead of k+2 # y = 1*k + . + n*k y += x*k pointList += [(x,y)] return fitExactPolynomial(pointList) def testFindCoefficientsOfPowerSum
So, let's turn this into code.
def fitExactPolynomial(pointList): n = len(pointList) #n=number of points degree = n - 1 # 1. make A A = make2dList(n,n) #allocating space for row in xrange(n): #row determines rth point of x&y we're dealing with for col in
observedX = solveSystemOfEquations(A,b) expectedX = [ [ 2 ], [ 3 ],  assert(almostEqualMatrices(observedX, expectedX) print "Passed!" def solveSystemOfEquations(A, b): return multiplyMatrices(invertMatrix(A), b) Next, we realize that given a set of poi
def invertMatrix(m): n = len(m) assert(len(m) = len(m) inverse = makeIdentity(n) for col in xrange(n): #proceeds 1 column at a time # 1. make the diagonal contain a 1 diagonalRow = col k = 1.0 / m[diagonalRow][col] #multiply the row by a constant (k) m
def checkForWin(puzzle, player): winningWord = player * 4 return (wordSearch(puzzle, winningWord) != None) # that was easy!
# # taken from wordSearch.py #
# wordSearch.py # This code was developed in class on Tue 4-Oct-2011. # As such, it may not contain
moveRow = getMoveRow(puzzle, moveCol) puzzle[moveRow][moveCol] = player printPuzzle(puzzle) if checkForWin(puzzle, player): print "* Player Wins! *" % player return moveCount += 1 player = "O" if (player = "X") else "X" print "* Tie Game! *"