Advertisement
franji

BinSearch

May 16th, 2018
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. from __future__ import division
  2. import unittest
  3.  
  4. ##  Binary Search ##
  5. ####################
  6.  
  7. # Problem: a function that accepts a SORTED list and an item x and returns first index of item >= x.
  8. # return len() if all items are smaller than x or if list is empty
  9. # note that x may appear several times in the list
  10. def BinSearchStupid(alist, x):
  11.     for i, y in enumerate(alist):
  12.         if y >= x:
  13.             return i
  14.     return len(alist)
  15.  
  16.  
  17.  
  18. class TestBinSearch(unittest.TestCase):
  19.  
  20.   def test_All(self):
  21.       funcs = [BinSearchStupid,
  22.                ]
  23.       for f in funcs:
  24.           self.do_func(f)
  25.  
  26.    def do_func(self, func):
  27.       a = [1,1,1,1,1,1]
  28.       i = func(a, 1)
  29.       self.assertEqual(0, i)
  30.       i = func(a, 2)
  31.       self.assertEqual(6, i)
  32.       a = [1,2,3,4,5]
  33.       i = func(a, 3)
  34.       self.assertEqual(2, i)
  35.       a = [1,2,3,4,5,6]
  36.       i = func(a, 3)
  37.       self.assertEqual(2, i)
  38.       a = [1,2,3,3,3,4,5,6]
  39.       i = func(a, 3)
  40.       self.assertEqual(2, i)
  41.       a = [1,2,4,4,4,4,5,6]
  42.       i = func(a, 3)
  43.       self.assertEqual(2, i)
  44.       a = []
  45.       i = func(a, 3)
  46.       self.assertEqual(0, i)
  47.       a = [3]
  48.       i = func(a, 3)
  49.       self.assertEqual(0, i)
  50.       i = func(a, 4)
  51.       self.assertEqual(1, i)
  52.       a = [3,3]
  53.       i = func(a, 3)
  54.       self.assertEqual(0, i)
  55.       i = func(a, 4)
  56.       self.assertEqual(2, i)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement