Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ############################
- # "gray code" for @contract
- # include this, but do not worry about how it works!
- ############################
- import functools
- def contract(f):
- def callIfExists(fn, suffix, *args, **kwargs):
- fnName = fn.__name__ + suffix
- if (fnName in globals()): return globals()[fnName](*args, **kwargs)
- @functools.wraps(f)
- def wrapper(*args, **kwargs):
- if (__debug__):
- reqResult = callIfExists(f, "_requires", *args, **kwargs)
- result = f(*args, **kwargs)
- if (__debug__):
- if (reqResult == None):
- callIfExists(f, "_ensures", result, *args, **kwargs)
- else:
- callIfExists(f, "_ensures", reqResult, result, *args, **kwargs)
- return result
- return wrapper
- ############################
- import string
- import copy
- @contract
- def mostCommonName(lst):
- lst.sort() #sorts lst for easy evaluation
- counter1, counter2 = 1, 0 #counters for highest freq name and currentname
- currentname = '' #the name that will be compared for counter2
- if len(lst) < 1: #returns none for empty lists
- return
- endlist = [lst[0]] # first name is starting name
- for i in xrange(1, len(lst)):
- if lst[i] in endlist: #if the name is in there, it applies to counter1
- counter1 += 1 #and thus, increases the counter
- if len(endlist) > 1: #if there are two or more elements
- endlist = [lst[i]] #the examined element is max and is added
- elif lst[i] == currentname: #counts the current examined name
- counter2 += 1 #every time it appears, it is counted
- else:
- currentname = lst[i] #in this case, it is a new name and...
- counter2 = 1 #restarts counter2
- if counter2 == counter1: #if they are equal...
- endlist = endlist + [lst[i]] #adds it to the list
- return endlist
- def mostCommonName_requires(lst):
- assert(isinstance(lst,list)) #makes sure that lst is a list
- for name in lst:
- assert(isinstance(name,str)) #makes sure that all values in lst are strings
- def mostCommonName_ensures(endlist, lst):
- assert(isinstance(endlist,list) or isinstance(endlist,type(None)))
- #makes sure it either returns none or a list
- if type(endlist) == list: #if it's not none...
- for name in endlist: #makes sure endlist only contains names from lst
- assert(name in lst)
- def testmostCommonName():
- print "Testing mostCommonName..."
- assert(mostCommonName(["Jane", "Aaron", "Cindy", "Aaron"]) == ["Aaron"])
- assert(mostCommonName([]) == None)
- assert(mostCommonName(["Jane"]) == (["Jane"]))
- assert(mostCommonName(["Aaron","Jane","Jane","Aaron", "Cindy"]) == ["Aaron", "Jane"])
- assert(mostCommonName(["Aaron","Jane","Jane","Aaron", "Cindy", "AARON"]) == ["Aaron", "Jane"])
- assert(mostCommonName(["Aaron", "Aaron", "Jane","Jane", "Cindy", "Cindy", "Jane"]) == ["Jane"])
- print "Passed!"
- testmostCommonName()
- @contract
- def areaOfPolygon(points):
- sum = 0
- if len(points) < 3:
- return sum
- for i in xrange(-1, len(points)-1): #so it doesn't go over the list, also
- #it starts at -1 so that it takes the last value and compares it
- #with the first, which is part of the formula
- sum += pointdifference(points, i) #adds pointdifference (below) to sum
- return abs(sum) / 2.0
- def pointdifference(pointlist, i): #given i and the pointlist, it performs
- #the operation for each pair, multiplication and subtraction
- firstpoint = pointlist[i] #the following variables represent points...
- secondpoint = pointlist[i + 1]
- multiple1 = firstpoint[0] * secondpoint[1] #and the x and y values
- multiple2 = secondpoint[0] * firstpoint[1]
- return multiple1 - multiple2
- def almostEqual(x1, x2): #helps to test functions with almost equal
- epsillon = 0.001 #the test value used in the autograder
- print abs(x1 - x2)
- if abs(x1 - x2) <= epsillon:
- return True
- else: return False
- def isReal(value):
- return (isinstance(value,float) or isinstance(value,int) or isinstance(value,long))
- def areaOfPolygon_requires(points):
- assert(isinstance(points,list)) #makes sure points is a list
- for value1 in points: #makes sure all values in the list are tuples
- assert(isinstance(value1,tuple))
- assert(len(value1) == 2) #and that all tuples contain exactly 2 points
- for value2 in value1: #makes sure all points are real values
- assert(isReal(value2))
- def areaOfPolygon_ensures(result, points):
- assert(isReal(result) and result > 0) #makes sure it's greater than 0 and
- #result is a number
- def testareaOfPolygon():
- print "Testing areaOfPolygon..."
- assert(almostEqual(areaOfPolygon([(4,10), (9,7), (11,2), (2,2)]), 45.5))
- assert(almostEqual(areaOfPolygon([(4,9),(10,11),(11,8),(4,7)]),17.0))
- print "Passed!"
- testareaOfPolygon()
- @contract
- def linearRegression(points):
- #first we find average x and y
- avgX = findAverage(points,0) #0 denotes x values
- avgY = findAverage(points,1) #1 denotes y values
- ssxx = ssxy = ssdev = ssres = 0 #values for later
- for pair in points: #this finds the difference product of the proper values
- ssxx += findDifferenceProduct(pair[0],pair[0], avgX, avgX) #then adds
- ssxy += findDifferenceProduct(pair[0],pair[1], avgX, avgY) #accordingly
- ssdev += findDifferenceProduct(pair[1],pair[1],avgY,avgY)
- a = ssxy / ssxx #a is found by the quotient of these
- b = (avgY - (avgX * a)) #b is found by using y = ax + b (b = y - ax)
- for pair in points: #for ssres
- yi = (a * pair[0] + b) #yi = ax + b where i is respective pair
- ssres += findDifferenceProduct(pair[1],pair[1],yi,yi) #uses yi instead
- #of an average value in this case
- r = ((ssdev - ssres) / ssdev) ** 0.5
- return (a,b,r)
- def findAverage(points, number): #takes the average of x or y
- average = 0.0
- for pair in points:
- average += pair[number]
- return average / len(points)
- def findDifferenceProduct(value1, value2, avg1, avg2): #takes values and then
- difference1 = value1 - avg1 #performs the proper subtraction
- #example: if it is ssxx then it will square differences
- #by multiplying by itself
- difference2 = value2 - avg2 #if it's ssxy, then it will multiply proper
- return difference1 * difference2 #subtractions
- def linearRegression_requires(points):
- assert(isinstance(points,list)) #makes sure it's a list
- for tuples in points: #for all values in points
- assert(isinstance(tuples,tuple)) #makes sure all values are tuples
- for numbers in tuples:
- assert(isReal(numbers))
- def linearRegression_ensures(result,points):
- assert(isinstance(result,tuple) and len(result) == 3)
- for values in result:
- assert(isinstance(values,float))
- def testlinearRegression():
- print "Testing linearRegression..."
- points1 = [(1,3),(2,5),(4,8)]
- print linearRegression(points1)
- assert(almostEqual(linearRegression(points1)[0],1.64))
- assert(almostEqual(linearRegression(points1)[1],1.51))
- assert(almostEqual(linearRegression(points1)[2],0.997))
- print "Passed!"
- #testlinearRegression()
- @contract
- def isLegalSudoku(board):
- length = len(board)
- for i in xrange(length): #for all values 0-N^2
- if not (isLegalRow(board, i) and isLegalCol(board, i) #if any are false
- and isLegalBlock(board, i)): #it will return false
- return False
- return True
- def isLegalSudoku_requires(board):
- for rows in xrange(len(board)):
- sudokuContractHelper2(board,rows) #calls contract helper for all values
- #that are in the range
- sudokuContractHelper1(board[rows]) #calls contract helper for all rows
- def isLegalSudoku_ensures(result,board):
- assert(isinstance(result,bool)) #makes sure it returns a boolean
- @contract
- def areLegalValues(values):
- length = len(values) #easy to use variable
- valuescopy = copy.copy(values) #so later operations don't damage the list
- for i in values:
- valuescopy.remove(i) #removes said instance of i in the copy array
- if i in valuescopy and i != 0: #if there is another instance of i
- return False #and it is not 0, it is illegal
- return True #has checked all values
- def sudokuContractHelper1(values): #for the lists in the board
- assert(isinstance(values,list)) #makes sure values is a list
- assert(isPerfectSquare(len(values))) #makes sure length is a perfect square
- for number in values:
- assert(isinstance(number,int)) #all values made sure to be ints
- assert(0 <= number <= len(values)) #all values between the parameters
- def sudokuContractHelper2(board,number):
- assert(isinstance(board,list) and isinstance(number,int)) #checks for types
- assert(0 <= number <= len(board) - 1) #checks if number is in parameters
- assert(isPerfectSquare(len(board)))
- def areLegalValues_requires(values):
- sudokuContractHelper1(values) #calls helper function which checks all...
- #that this function requires
- def areLegalValues_ensures(result, values):
- assert(isinstance(result,bool)) #checks to make sure if boolean
- def isPerfectSquare(n):
- root = n ** 0.5
- return (int(root) ** 2 == n)
- @contract
- def isLegalRow(board, row): #since board only contains a list of lists of ints
- return areLegalValues(board[row]) #all that is required is areLegalValues
- #of the row of the board
- def isLegalRow_requires(board, row):
- sudokuContractHelper2(board, row)
- for rows in board: #for all the rows in the list, calls the helper
- sudokuContractHelper1(rows) #to test all the lists within
- def isLegalRow_ensures(result,board,row):
- assert(isinstance(result,bool)) #only needs to check if boolean
- @contract
- def isLegalCol(board,col):
- colalias = [] #creates a new list for the col
- length = len(board)
- for i in xrange(length):
- colalias += [board[i][col]] #adds the number in the proper index
- return areLegalValues(colalias)
- def isLegalCol_requires(board,col):
- sudokuContractHelper2(board,col) #this helper function does all required
- for rows in board: #tests all the lists within
- sudokuContractHelper1(rows)
- def isLegalCol_ensures(result,board,col):
- assert(isinstance(result,bool)) #only needs to check if boolean
- @contract
- def isLegalBlock(board, block):
- blockalias = []
- length = len(board)
- nvalue = int(length ** 0.5) #this describes the nxn dimensions of the box
- blockrow = nvalue * (block / nvalue) #y placement is gotten via division
- blockcol = nvalue * (block % nvalue) #x placement is gotten via modulus
- for row in xrange(blockrow, blockrow + nvalue): #goes over lists in rows
- for col in xrange(blockcol, blockcol + nvalue): #goes over the cols
- blockalias += [board[row][col]]
- return areLegalValues(blockalias)
- def isLegalBlock_requires(board,block):
- sudokuContractHelper2(board,block) #tests the board issues
- for rows in board: #as with before, it tests all the lists within
- sudokuContractHelper1(rows)
- def isLegalBlock_ensures(result,board,block):
- assert(isinstance(result,bool)) #makes sure it's a boolean
- def testareLegalValues():
- print "Testing areLegalValues..."
- try:
- areLegalValues([5,4,2,4,2])
- print "test1 failed"
- except:
- print"test1 passed!"
- assert(areLegalValues([5,1,3,2,6,9,4,8,7]) == True)
- assert(areLegalValues([0,1,5,3,2,0,4,0,9]) == True)
- try:
- areLegalValues([1,5,4,3,2,12,9,6,11,8,10,7])
- print "test4 failed"
- except:
- print "test4 passed!"
- assert(areLegalValues([1,6,0,15,7,4,0,11,10,0,0,3,2,0,16,0]) == True)
- assert(areLegalValues([1]) == True)
- assert(areLegalValues([0]) == True)
- print "Done!"
- testareLegalValues()
- def boardtestgenerator():
- board1 = [[1,2,0,3],[0,1,0,0],[1,3,2,0],[0,0,0,0]]
- board2 = [[0,2,1,0],[1,0,2,0],[0,1,3,3],[0,3,2,0]]
- board3 = [[0,1,6,2,3,0,4,0,0],[9,2,4,0,0,6,8,1,7],[7,3,5,1,0,9,2,0,0]]
- board4 = [[4,0,2,0,0,0,0,0,0],[0,6,3,0,7,2,1,0,0],[0,0,0,0,0,9,8,0,0],[0,2,8,0,6,1,0,4,9],[7,0,1,0,4,8,0,0,3],[5,4,0,3,0,0,2,0,0],[0,0,0,0,0,0,0,7,5],[6,1,0,7,5,0,9,0,0],[2,0,5,9,8,6,0,3,1]]
- return (board1, board2, board3,board4)
- def boardprinter(board):
- for i in board:
- print i
- print
- return
- def testisLegalRow():
- print "Testing isLegalRow..."
- x = boardtestgenerator()
- assert(isLegalRow(x[0], 0) == True)
- assert(isLegalRow(x[0], 1) == True)
- try:
- isLegalRow(x[1], 1)
- print "test3 failed"
- except:
- print "test3 passed!"
- assert(isLegalRow(x[1], 2) == False)
- print "Done!"
- testisLegalRow()
- def testisLegalCol():
- print "Testing isLegalCol..."
- x = boardtestgenerator()
- assert(isLegalCol(x[0],0) == False)
- assert(isLegalCol(x[3],4) == True)
- print "Done!"
- def testisLegalBlock():
- print "Testing isLegalBlock..."
- x = boardtestgenerator()
- assert(isLegalBlock(x[0],0) == False)
- assert(isLegalBlock(x[3],0) == True)
- assert(isLegalBlock(x[3],1) == True)
- assert(isLegalBlock(x[3],8) == True)
- print "Done!"
- def testisLegalSudoku():
- x = boardtestgenerator()
- print "Testing isLegalSudoku..."
- assert(isLegalSudoku(x[0]) == False)
- assert(isLegalSudoku(x[3]) == True)
- assert(isLegalSudoku(x[1]) == False)
- try:
- isLegalSudoku(x[2])
- print "test 4 failed"
- except:
- print "test 4 passed!"
- print "Done!"
- testisLegalCol()
- testisLegalBlock()
- testisLegalSudoku()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement