Advertisement
lackofcheese

test3x3.py

Sep 10th, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. from creamsteak import creamsteak
  2. import itertools
  3. import numpy as np
  4. import time
  5.  
  6. def easy_3x3(vals):
  7.     inds = np.argsort(vals)
  8.     ii, jj = np.unravel_index(inds[:3], (3, 3))
  9.  
  10.     vals.sort()
  11.     total = vals[4:].sum()
  12.     if ii[0] == ii[1] == ii[2] or jj[0] == jj[1] == jj[2]:
  13.         return total + vals[2]
  14.     return total + vals[3]
  15.  
  16. def hard_3x3(vals):
  17.     return creamsteak(vals.reshape(3, 3))[0]
  18.  
  19. def do_tests(tests, func=easy_3x3,
  20.              numTests=np.inf, showProg=False, freq=1000,
  21.              name=''):
  22.     print "--------------------------------------------"
  23.     print 'BEGIN TEST:', name
  24.     print 'Maximum # of test cases:', numTests
  25.     print "--------------------------------------------"
  26.     start = time.clock()
  27.     total = 0
  28.     count = 0
  29.     prog = 0
  30.     for vals in tests:
  31.         vals = np.array(vals)
  32.         total += func(vals)
  33.         count += 1
  34.         if count >= numTests:
  35.             break
  36.        
  37.         if not showProg or numTests == np.inf:
  38.             continue
  39.         newProg = count * freq / numTests
  40.         if newProg > prog:
  41.             prog = newProg
  42.             print 'Completed {} of {} tests ({.2f}%)'.format(count, numTests,
  43.                                                              prog*100.0/freq)
  44.     print "BigBoss =", total
  45.     print "BigCount =", count
  46.     print 'Time taken: {:.2f}s'.format(time.clock()-start)
  47.     print "-----------------END TEST-------------------"
  48.     print
  49.  
  50. def all_3x3():
  51.     return itertools.product(xrange(1, 10), repeat=9)
  52.  
  53. def from_file(filename):
  54.     nums = []
  55.     with open(filename) as f:
  56.         for line in f:
  57.             toks = line.split(',')
  58.             if len(toks) > 1:
  59.                 for tok in toks:
  60.                     nums.append(int(tok))
  61.             else:
  62.                 yield nums
  63.                 nums = []
  64.     if len(nums) > 0:
  65.         yield nums
  66.  
  67. if __name__=='__main__':
  68.     nt = 10**5
  69.     do_tests(all_3x3(), easy_3x3, nt, name='All 3x3 cases w/ shortcut')
  70.     do_tests(all_3x3(), hard_3x3, nt, name='All 3x3 cases using creamsteak()')
  71.     do_tests(from_file("Bunch_o'_matrices.txt"), easy_3x3, name='From file w/ shortcut')
  72.     do_tests(from_file("Bunch_o'_matrices.txt"), hard_3x3, name='From file using creamsteak()')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement