Advertisement
Divock

old sudoku code

Feb 2nd, 2016
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.68 KB | None | 0 0
  1. ############################
  2. # "gray code" for @contract
  3. # include this, but do not worry about how it works!
  4. ############################
  5. import functools
  6. def contract(f):
  7. def callIfExists(fn, suffix, *args, **kwargs):
  8. fnName = fn.__name__ + suffix
  9. if (fnName in globals()): return globals()[fnName](*args, **kwargs)
  10. @functools.wraps(f)
  11. def wrapper(*args, **kwargs):
  12. if (__debug__):
  13. reqResult = callIfExists(f, "_requires", *args, **kwargs)
  14. result = f(*args, **kwargs)
  15. if (__debug__):
  16. if (reqResult == None):
  17. callIfExists(f, "_ensures", result, *args, **kwargs)
  18. else:
  19. callIfExists(f, "_ensures", reqResult, result, *args, **kwargs)
  20. return result
  21. return wrapper
  22. ############################
  23.  
  24.  
  25. import string
  26. import copy
  27.  
  28. @contract
  29. def mostCommonName(lst):
  30. lst.sort() #sorts lst for easy evaluation
  31. counter1, counter2 = 1, 0 #counters for highest freq name and currentname
  32. currentname = '' #the name that will be compared for counter2
  33. if len(lst) < 1: #returns none for empty lists
  34. return
  35. endlist = [lst[0]] # first name is starting name
  36. for i in xrange(1, len(lst)):
  37. if lst[i] in endlist: #if the name is in there, it applies to counter1
  38. counter1 += 1 #and thus, increases the counter
  39. if len(endlist) > 1: #if there are two or more elements
  40. endlist = [lst[i]] #the examined element is max and is added
  41. elif lst[i] == currentname: #counts the current examined name
  42. counter2 += 1 #every time it appears, it is counted
  43. else:
  44. currentname = lst[i] #in this case, it is a new name and...
  45. counter2 = 1 #restarts counter2
  46. if counter2 == counter1: #if they are equal...
  47. endlist = endlist + [lst[i]] #adds it to the list
  48. return endlist
  49.  
  50. def mostCommonName_requires(lst):
  51. assert(isinstance(lst,list)) #makes sure that lst is a list
  52. for name in lst:
  53. assert(isinstance(name,str)) #makes sure that all values in lst are strings
  54.  
  55. def mostCommonName_ensures(endlist, lst):
  56. assert(isinstance(endlist,list) or isinstance(endlist,type(None)))
  57. #makes sure it either returns none or a list
  58. if type(endlist) == list: #if it's not none...
  59. for name in endlist: #makes sure endlist only contains names from lst
  60. assert(name in lst)
  61.  
  62. def testmostCommonName():
  63. print "Testing mostCommonName..."
  64. assert(mostCommonName(["Jane", "Aaron", "Cindy", "Aaron"]) == ["Aaron"])
  65. assert(mostCommonName([]) == None)
  66. assert(mostCommonName(["Jane"]) == (["Jane"]))
  67. assert(mostCommonName(["Aaron","Jane","Jane","Aaron", "Cindy"]) == ["Aaron", "Jane"])
  68. assert(mostCommonName(["Aaron","Jane","Jane","Aaron", "Cindy", "AARON"]) == ["Aaron", "Jane"])
  69. assert(mostCommonName(["Aaron", "Aaron", "Jane","Jane", "Cindy", "Cindy", "Jane"]) == ["Jane"])
  70. print "Passed!"
  71.  
  72.  
  73. testmostCommonName()
  74. @contract
  75. def areaOfPolygon(points):
  76. sum = 0
  77. if len(points) < 3:
  78. return sum
  79. for i in xrange(-1, len(points)-1): #so it doesn't go over the list, also
  80. #it starts at -1 so that it takes the last value and compares it
  81. #with the first, which is part of the formula
  82. sum += pointdifference(points, i) #adds pointdifference (below) to sum
  83. return abs(sum) / 2.0
  84.  
  85. def pointdifference(pointlist, i): #given i and the pointlist, it performs
  86. #the operation for each pair, multiplication and subtraction
  87. firstpoint = pointlist[i] #the following variables represent points...
  88. secondpoint = pointlist[i + 1]
  89. multiple1 = firstpoint[0] * secondpoint[1] #and the x and y values
  90. multiple2 = secondpoint[0] * firstpoint[1]
  91. return multiple1 - multiple2
  92.  
  93. def almostEqual(x1, x2): #helps to test functions with almost equal
  94. epsillon = 0.001 #the test value used in the autograder
  95. print abs(x1 - x2)
  96. if abs(x1 - x2) <= epsillon:
  97. return True
  98. else: return False
  99.  
  100. def isReal(value):
  101. return (isinstance(value,float) or isinstance(value,int) or isinstance(value,long))
  102.  
  103. def areaOfPolygon_requires(points):
  104. assert(isinstance(points,list)) #makes sure points is a list
  105. for value1 in points: #makes sure all values in the list are tuples
  106. assert(isinstance(value1,tuple))
  107. assert(len(value1) == 2) #and that all tuples contain exactly 2 points
  108. for value2 in value1: #makes sure all points are real values
  109. assert(isReal(value2))
  110.  
  111. def areaOfPolygon_ensures(result, points):
  112. assert(isReal(result) and result > 0) #makes sure it's greater than 0 and
  113. #result is a number
  114.  
  115. def testareaOfPolygon():
  116. print "Testing areaOfPolygon..."
  117. assert(almostEqual(areaOfPolygon([(4,10), (9,7), (11,2), (2,2)]), 45.5))
  118. assert(almostEqual(areaOfPolygon([(4,9),(10,11),(11,8),(4,7)]),17.0))
  119. print "Passed!"
  120.  
  121. testareaOfPolygon()
  122.  
  123. @contract
  124. def linearRegression(points):
  125. #first we find average x and y
  126. avgX = findAverage(points,0) #0 denotes x values
  127. avgY = findAverage(points,1) #1 denotes y values
  128. ssxx = ssxy = ssdev = ssres = 0 #values for later
  129. for pair in points: #this finds the difference product of the proper values
  130. ssxx += findDifferenceProduct(pair[0],pair[0], avgX, avgX) #then adds
  131. ssxy += findDifferenceProduct(pair[0],pair[1], avgX, avgY) #accordingly
  132. ssdev += findDifferenceProduct(pair[1],pair[1],avgY,avgY)
  133. a = ssxy / ssxx #a is found by the quotient of these
  134. b = (avgY - (avgX * a)) #b is found by using y = ax + b (b = y - ax)
  135. for pair in points: #for ssres
  136. yi = (a * pair[0] + b) #yi = ax + b where i is respective pair
  137. ssres += findDifferenceProduct(pair[1],pair[1],yi,yi) #uses yi instead
  138. #of an average value in this case
  139. r = ((ssdev - ssres) / ssdev) ** 0.5
  140. return (a,b,r)
  141.  
  142. def findAverage(points, number): #takes the average of x or y
  143. average = 0.0
  144. for pair in points:
  145. average += pair[number]
  146. return average / len(points)
  147.  
  148.  
  149. def findDifferenceProduct(value1, value2, avg1, avg2): #takes values and then
  150. difference1 = value1 - avg1 #performs the proper subtraction
  151. #example: if it is ssxx then it will square differences
  152. #by multiplying by itself
  153. difference2 = value2 - avg2 #if it's ssxy, then it will multiply proper
  154. return difference1 * difference2 #subtractions
  155.  
  156. def linearRegression_requires(points):
  157. assert(isinstance(points,list)) #makes sure it's a list
  158. for tuples in points: #for all values in points
  159. assert(isinstance(tuples,tuple)) #makes sure all values are tuples
  160. for numbers in tuples:
  161. assert(isReal(numbers))
  162.  
  163. def linearRegression_ensures(result,points):
  164. assert(isinstance(result,tuple) and len(result) == 3)
  165. for values in result:
  166. assert(isinstance(values,float))
  167.  
  168. def testlinearRegression():
  169. print "Testing linearRegression..."
  170. points1 = [(1,3),(2,5),(4,8)]
  171. print linearRegression(points1)
  172. assert(almostEqual(linearRegression(points1)[0],1.64))
  173. assert(almostEqual(linearRegression(points1)[1],1.51))
  174. assert(almostEqual(linearRegression(points1)[2],0.997))
  175. print "Passed!"
  176.  
  177. #testlinearRegression()
  178.  
  179. @contract
  180. def isLegalSudoku(board):
  181. length = len(board)
  182. for i in xrange(length): #for all values 0-N^2
  183. if not (isLegalRow(board, i) and isLegalCol(board, i) #if any are false
  184. and isLegalBlock(board, i)): #it will return false
  185. return False
  186. return True
  187.  
  188. def isLegalSudoku_requires(board):
  189. for rows in xrange(len(board)):
  190. sudokuContractHelper2(board,rows) #calls contract helper for all values
  191. #that are in the range
  192. sudokuContractHelper1(board[rows]) #calls contract helper for all rows
  193.  
  194. def isLegalSudoku_ensures(result,board):
  195. assert(isinstance(result,bool)) #makes sure it returns a boolean
  196.  
  197. @contract
  198. def areLegalValues(values):
  199. length = len(values) #easy to use variable
  200. valuescopy = copy.copy(values) #so later operations don't damage the list
  201. for i in values:
  202. valuescopy.remove(i) #removes said instance of i in the copy array
  203. if i in valuescopy and i != 0: #if there is another instance of i
  204. return False #and it is not 0, it is illegal
  205. return True #has checked all values
  206.  
  207. def sudokuContractHelper1(values): #for the lists in the board
  208. assert(isinstance(values,list)) #makes sure values is a list
  209. assert(isPerfectSquare(len(values))) #makes sure length is a perfect square
  210. for number in values:
  211. assert(isinstance(number,int)) #all values made sure to be ints
  212. assert(0 <= number <= len(values)) #all values between the parameters
  213.  
  214. def sudokuContractHelper2(board,number):
  215. assert(isinstance(board,list) and isinstance(number,int)) #checks for types
  216. assert(0 <= number <= len(board) - 1) #checks if number is in parameters
  217. assert(isPerfectSquare(len(board)))
  218.  
  219. def areLegalValues_requires(values):
  220. sudokuContractHelper1(values) #calls helper function which checks all...
  221. #that this function requires
  222.  
  223. def areLegalValues_ensures(result, values):
  224. assert(isinstance(result,bool)) #checks to make sure if boolean
  225.  
  226. def isPerfectSquare(n):
  227. root = n ** 0.5
  228. return (int(root) ** 2 == n)
  229.  
  230. @contract
  231. def isLegalRow(board, row): #since board only contains a list of lists of ints
  232. return areLegalValues(board[row]) #all that is required is areLegalValues
  233. #of the row of the board
  234.  
  235. def isLegalRow_requires(board, row):
  236. sudokuContractHelper2(board, row)
  237. for rows in board: #for all the rows in the list, calls the helper
  238. sudokuContractHelper1(rows) #to test all the lists within
  239.  
  240. def isLegalRow_ensures(result,board,row):
  241. assert(isinstance(result,bool)) #only needs to check if boolean
  242.  
  243. @contract
  244. def isLegalCol(board,col):
  245. colalias = [] #creates a new list for the col
  246. length = len(board)
  247. for i in xrange(length):
  248. colalias += [board[i][col]] #adds the number in the proper index
  249. return areLegalValues(colalias)
  250.  
  251. def isLegalCol_requires(board,col):
  252. sudokuContractHelper2(board,col) #this helper function does all required
  253. for rows in board: #tests all the lists within
  254. sudokuContractHelper1(rows)
  255.  
  256. def isLegalCol_ensures(result,board,col):
  257. assert(isinstance(result,bool)) #only needs to check if boolean
  258.  
  259. @contract
  260. def isLegalBlock(board, block):
  261. blockalias = []
  262. length = len(board)
  263. nvalue = int(length ** 0.5) #this describes the nxn dimensions of the box
  264. blockrow = nvalue * (block / nvalue) #y placement is gotten via division
  265. blockcol = nvalue * (block % nvalue) #x placement is gotten via modulus
  266. for row in xrange(blockrow, blockrow + nvalue): #goes over lists in rows
  267. for col in xrange(blockcol, blockcol + nvalue): #goes over the cols
  268. blockalias += [board[row][col]]
  269. return areLegalValues(blockalias)
  270.  
  271. def isLegalBlock_requires(board,block):
  272. sudokuContractHelper2(board,block) #tests the board issues
  273. for rows in board: #as with before, it tests all the lists within
  274. sudokuContractHelper1(rows)
  275.  
  276. def isLegalBlock_ensures(result,board,block):
  277. assert(isinstance(result,bool)) #makes sure it's a boolean
  278.  
  279. def testareLegalValues():
  280. print "Testing areLegalValues..."
  281. try:
  282. areLegalValues([5,4,2,4,2])
  283. print "test1 failed"
  284. except:
  285. print"test1 passed!"
  286. assert(areLegalValues([5,1,3,2,6,9,4,8,7]) == True)
  287. assert(areLegalValues([0,1,5,3,2,0,4,0,9]) == True)
  288. try:
  289. areLegalValues([1,5,4,3,2,12,9,6,11,8,10,7])
  290. print "test4 failed"
  291. except:
  292. print "test4 passed!"
  293. assert(areLegalValues([1,6,0,15,7,4,0,11,10,0,0,3,2,0,16,0]) == True)
  294. assert(areLegalValues([1]) == True)
  295. assert(areLegalValues([0]) == True)
  296. print "Done!"
  297.  
  298. testareLegalValues()
  299.  
  300. def boardtestgenerator():
  301. board1 = [[1,2,0,3],[0,1,0,0],[1,3,2,0],[0,0,0,0]]
  302. board2 = [[0,2,1,0],[1,0,2,0],[0,1,3,3],[0,3,2,0]]
  303. 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]]
  304. 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]]
  305. return (board1, board2, board3,board4)
  306.  
  307. def boardprinter(board):
  308. for i in board:
  309. print i
  310. print
  311. return
  312.  
  313. def testisLegalRow():
  314. print "Testing isLegalRow..."
  315. x = boardtestgenerator()
  316. assert(isLegalRow(x[0], 0) == True)
  317. assert(isLegalRow(x[0], 1) == True)
  318. try:
  319. isLegalRow(x[1], 1)
  320. print "test3 failed"
  321. except:
  322. print "test3 passed!"
  323. assert(isLegalRow(x[1], 2) == False)
  324. print "Done!"
  325.  
  326. testisLegalRow()
  327.  
  328. def testisLegalCol():
  329. print "Testing isLegalCol..."
  330. x = boardtestgenerator()
  331. assert(isLegalCol(x[0],0) == False)
  332. assert(isLegalCol(x[3],4) == True)
  333. print "Done!"
  334.  
  335. def testisLegalBlock():
  336. print "Testing isLegalBlock..."
  337. x = boardtestgenerator()
  338. assert(isLegalBlock(x[0],0) == False)
  339. assert(isLegalBlock(x[3],0) == True)
  340. assert(isLegalBlock(x[3],1) == True)
  341. assert(isLegalBlock(x[3],8) == True)
  342. print "Done!"
  343.  
  344. def testisLegalSudoku():
  345. x = boardtestgenerator()
  346. print "Testing isLegalSudoku..."
  347. assert(isLegalSudoku(x[0]) == False)
  348. assert(isLegalSudoku(x[3]) == True)
  349. assert(isLegalSudoku(x[1]) == False)
  350. try:
  351. isLegalSudoku(x[2])
  352. print "test 4 failed"
  353. except:
  354. print "test 4 passed!"
  355. print "Done!"
  356.  
  357. testisLegalCol()
  358. testisLegalBlock()
  359. testisLegalSudoku()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement