test_bisect.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import sys
  2. import unittest
  3. from test.support import import_helper
  4. from collections import UserList
  5. py_bisect = import_helper.import_fresh_module('bisect', blocked=['_bisect'])
  6. c_bisect = import_helper.import_fresh_module('bisect', fresh=['_bisect'])
  7. class Range(object):
  8. """A trivial range()-like object that has an insert() method."""
  9. def __init__(self, start, stop):
  10. self.start = start
  11. self.stop = stop
  12. self.last_insert = None
  13. def __len__(self):
  14. return self.stop - self.start
  15. def __getitem__(self, idx):
  16. n = self.stop - self.start
  17. if idx < 0:
  18. idx += n
  19. if idx >= n:
  20. raise IndexError(idx)
  21. return self.start + idx
  22. def insert(self, idx, item):
  23. self.last_insert = idx, item
  24. class TestBisect:
  25. def setUp(self):
  26. self.precomputedCases = [
  27. (self.module.bisect_right, [], 1, 0),
  28. (self.module.bisect_right, [1], 0, 0),
  29. (self.module.bisect_right, [1], 1, 1),
  30. (self.module.bisect_right, [1], 2, 1),
  31. (self.module.bisect_right, [1, 1], 0, 0),
  32. (self.module.bisect_right, [1, 1], 1, 2),
  33. (self.module.bisect_right, [1, 1], 2, 2),
  34. (self.module.bisect_right, [1, 1, 1], 0, 0),
  35. (self.module.bisect_right, [1, 1, 1], 1, 3),
  36. (self.module.bisect_right, [1, 1, 1], 2, 3),
  37. (self.module.bisect_right, [1, 1, 1, 1], 0, 0),
  38. (self.module.bisect_right, [1, 1, 1, 1], 1, 4),
  39. (self.module.bisect_right, [1, 1, 1, 1], 2, 4),
  40. (self.module.bisect_right, [1, 2], 0, 0),
  41. (self.module.bisect_right, [1, 2], 1, 1),
  42. (self.module.bisect_right, [1, 2], 1.5, 1),
  43. (self.module.bisect_right, [1, 2], 2, 2),
  44. (self.module.bisect_right, [1, 2], 3, 2),
  45. (self.module.bisect_right, [1, 1, 2, 2], 0, 0),
  46. (self.module.bisect_right, [1, 1, 2, 2], 1, 2),
  47. (self.module.bisect_right, [1, 1, 2, 2], 1.5, 2),
  48. (self.module.bisect_right, [1, 1, 2, 2], 2, 4),
  49. (self.module.bisect_right, [1, 1, 2, 2], 3, 4),
  50. (self.module.bisect_right, [1, 2, 3], 0, 0),
  51. (self.module.bisect_right, [1, 2, 3], 1, 1),
  52. (self.module.bisect_right, [1, 2, 3], 1.5, 1),
  53. (self.module.bisect_right, [1, 2, 3], 2, 2),
  54. (self.module.bisect_right, [1, 2, 3], 2.5, 2),
  55. (self.module.bisect_right, [1, 2, 3], 3, 3),
  56. (self.module.bisect_right, [1, 2, 3], 4, 3),
  57. (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 0, 0),
  58. (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1, 1),
  59. (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1.5, 1),
  60. (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2, 3),
  61. (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2.5, 3),
  62. (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3, 6),
  63. (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3.5, 6),
  64. (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 4, 10),
  65. (self.module.bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 5, 10),
  66. (self.module.bisect_left, [], 1, 0),
  67. (self.module.bisect_left, [1], 0, 0),
  68. (self.module.bisect_left, [1], 1, 0),
  69. (self.module.bisect_left, [1], 2, 1),
  70. (self.module.bisect_left, [1, 1], 0, 0),
  71. (self.module.bisect_left, [1, 1], 1, 0),
  72. (self.module.bisect_left, [1, 1], 2, 2),
  73. (self.module.bisect_left, [1, 1, 1], 0, 0),
  74. (self.module.bisect_left, [1, 1, 1], 1, 0),
  75. (self.module.bisect_left, [1, 1, 1], 2, 3),
  76. (self.module.bisect_left, [1, 1, 1, 1], 0, 0),
  77. (self.module.bisect_left, [1, 1, 1, 1], 1, 0),
  78. (self.module.bisect_left, [1, 1, 1, 1], 2, 4),
  79. (self.module.bisect_left, [1, 2], 0, 0),
  80. (self.module.bisect_left, [1, 2], 1, 0),
  81. (self.module.bisect_left, [1, 2], 1.5, 1),
  82. (self.module.bisect_left, [1, 2], 2, 1),
  83. (self.module.bisect_left, [1, 2], 3, 2),
  84. (self.module.bisect_left, [1, 1, 2, 2], 0, 0),
  85. (self.module.bisect_left, [1, 1, 2, 2], 1, 0),
  86. (self.module.bisect_left, [1, 1, 2, 2], 1.5, 2),
  87. (self.module.bisect_left, [1, 1, 2, 2], 2, 2),
  88. (self.module.bisect_left, [1, 1, 2, 2], 3, 4),
  89. (self.module.bisect_left, [1, 2, 3], 0, 0),
  90. (self.module.bisect_left, [1, 2, 3], 1, 0),
  91. (self.module.bisect_left, [1, 2, 3], 1.5, 1),
  92. (self.module.bisect_left, [1, 2, 3], 2, 1),
  93. (self.module.bisect_left, [1, 2, 3], 2.5, 2),
  94. (self.module.bisect_left, [1, 2, 3], 3, 2),
  95. (self.module.bisect_left, [1, 2, 3], 4, 3),
  96. (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 0, 0),
  97. (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1, 0),
  98. (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1.5, 1),
  99. (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2, 1),
  100. (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2.5, 3),
  101. (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3, 3),
  102. (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3.5, 6),
  103. (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 4, 6),
  104. (self.module.bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 5, 10)
  105. ]
  106. def test_precomputed(self):
  107. for func, data, elem, expected in self.precomputedCases:
  108. self.assertEqual(func(data, elem), expected)
  109. self.assertEqual(func(UserList(data), elem), expected)
  110. def test_negative_lo(self):
  111. # Issue 3301
  112. mod = self.module
  113. self.assertRaises(ValueError, mod.bisect_left, [1, 2, 3], 5, -1, 3)
  114. self.assertRaises(ValueError, mod.bisect_right, [1, 2, 3], 5, -1, 3)
  115. self.assertRaises(ValueError, mod.insort_left, [1, 2, 3], 5, -1, 3)
  116. self.assertRaises(ValueError, mod.insort_right, [1, 2, 3], 5, -1, 3)
  117. def test_large_range(self):
  118. # Issue 13496
  119. mod = self.module
  120. n = sys.maxsize
  121. data = range(n-1)
  122. self.assertEqual(mod.bisect_left(data, n-3), n-3)
  123. self.assertEqual(mod.bisect_right(data, n-3), n-2)
  124. self.assertEqual(mod.bisect_left(data, n-3, n-10, n), n-3)
  125. self.assertEqual(mod.bisect_right(data, n-3, n-10, n), n-2)
  126. def test_large_pyrange(self):
  127. # Same as above, but without C-imposed limits on range() parameters
  128. mod = self.module
  129. n = sys.maxsize
  130. data = Range(0, n-1)
  131. self.assertEqual(mod.bisect_left(data, n-3), n-3)
  132. self.assertEqual(mod.bisect_right(data, n-3), n-2)
  133. self.assertEqual(mod.bisect_left(data, n-3, n-10, n), n-3)
  134. self.assertEqual(mod.bisect_right(data, n-3, n-10, n), n-2)
  135. x = n - 100
  136. mod.insort_left(data, x, x - 50, x + 50)
  137. self.assertEqual(data.last_insert, (x, x))
  138. x = n - 200
  139. mod.insort_right(data, x, x - 50, x + 50)
  140. self.assertEqual(data.last_insert, (x + 1, x))
  141. def test_random(self, n=25):
  142. from random import randrange
  143. for i in range(n):
  144. data = [randrange(0, n, 2) for j in range(i)]
  145. data.sort()
  146. elem = randrange(-1, n+1)
  147. ip = self.module.bisect_left(data, elem)
  148. if ip < len(data):
  149. self.assertTrue(elem <= data[ip])
  150. if ip > 0:
  151. self.assertTrue(data[ip-1] < elem)
  152. ip = self.module.bisect_right(data, elem)
  153. if ip < len(data):
  154. self.assertTrue(elem < data[ip])
  155. if ip > 0:
  156. self.assertTrue(data[ip-1] <= elem)
  157. def test_optionalSlicing(self):
  158. for func, data, elem, expected in self.precomputedCases:
  159. for lo in range(4):
  160. lo = min(len(data), lo)
  161. for hi in range(3,8):
  162. hi = min(len(data), hi)
  163. ip = func(data, elem, lo, hi)
  164. self.assertTrue(lo <= ip <= hi)
  165. if func is self.module.bisect_left and ip < hi:
  166. self.assertTrue(elem <= data[ip])
  167. if func is self.module.bisect_left and ip > lo:
  168. self.assertTrue(data[ip-1] < elem)
  169. if func is self.module.bisect_right and ip < hi:
  170. self.assertTrue(elem < data[ip])
  171. if func is self.module.bisect_right and ip > lo:
  172. self.assertTrue(data[ip-1] <= elem)
  173. self.assertEqual(ip, max(lo, min(hi, expected)))
  174. def test_backcompatibility(self):
  175. self.assertEqual(self.module.bisect, self.module.bisect_right)
  176. def test_keyword_args(self):
  177. data = [10, 20, 30, 40, 50]
  178. self.assertEqual(self.module.bisect_left(a=data, x=25, lo=1, hi=3), 2)
  179. self.assertEqual(self.module.bisect_right(a=data, x=25, lo=1, hi=3), 2)
  180. self.assertEqual(self.module.bisect(a=data, x=25, lo=1, hi=3), 2)
  181. self.module.insort_left(a=data, x=25, lo=1, hi=3)
  182. self.module.insort_right(a=data, x=25, lo=1, hi=3)
  183. self.module.insort(a=data, x=25, lo=1, hi=3)
  184. self.assertEqual(data, [10, 20, 25, 25, 25, 30, 40, 50])
  185. def test_lookups_with_key_function(self):
  186. mod = self.module
  187. # Invariant: Index with a keyfunc on an array
  188. # should match the index on an array where
  189. # key function has already been applied.
  190. keyfunc = abs
  191. arr = sorted([2, -4, 6, 8, -10], key=keyfunc)
  192. precomputed_arr = list(map(keyfunc, arr))
  193. for x in precomputed_arr:
  194. self.assertEqual(
  195. mod.bisect_left(arr, x, key=keyfunc),
  196. mod.bisect_left(precomputed_arr, x)
  197. )
  198. self.assertEqual(
  199. mod.bisect_right(arr, x, key=keyfunc),
  200. mod.bisect_right(precomputed_arr, x)
  201. )
  202. keyfunc = str.casefold
  203. arr = sorted('aBcDeEfgHhiIiij', key=keyfunc)
  204. precomputed_arr = list(map(keyfunc, arr))
  205. for x in precomputed_arr:
  206. self.assertEqual(
  207. mod.bisect_left(arr, x, key=keyfunc),
  208. mod.bisect_left(precomputed_arr, x)
  209. )
  210. self.assertEqual(
  211. mod.bisect_right(arr, x, key=keyfunc),
  212. mod.bisect_right(precomputed_arr, x)
  213. )
  214. def test_insort(self):
  215. from random import shuffle
  216. mod = self.module
  217. # Invariant: As random elements are inserted in
  218. # a target list, the targetlist remains sorted.
  219. keyfunc = abs
  220. data = list(range(-10, 11)) + list(range(-20, 20, 2))
  221. shuffle(data)
  222. target = []
  223. for x in data:
  224. mod.insort_left(target, x, key=keyfunc)
  225. self.assertEqual(
  226. sorted(target, key=keyfunc),
  227. target
  228. )
  229. target = []
  230. for x in data:
  231. mod.insort_right(target, x, key=keyfunc)
  232. self.assertEqual(
  233. sorted(target, key=keyfunc),
  234. target
  235. )
  236. def test_insort_keynotNone(self):
  237. x = []
  238. y = {"a": 2, "b": 1}
  239. for f in (self.module.insort_left, self.module.insort_right):
  240. self.assertRaises(TypeError, f, x, y, key = "b")
  241. class TestBisectPython(TestBisect, unittest.TestCase):
  242. module = py_bisect
  243. class TestBisectC(TestBisect, unittest.TestCase):
  244. module = c_bisect
  245. #==============================================================================
  246. class TestInsort:
  247. def test_vsBuiltinSort(self, n=500):
  248. from random import choice
  249. for insorted in (list(), UserList()):
  250. for i in range(n):
  251. digit = choice("0123456789")
  252. if digit in "02468":
  253. f = self.module.insort_left
  254. else:
  255. f = self.module.insort_right
  256. f(insorted, digit)
  257. self.assertEqual(sorted(insorted), insorted)
  258. def test_backcompatibility(self):
  259. self.assertEqual(self.module.insort, self.module.insort_right)
  260. def test_listDerived(self):
  261. class List(list):
  262. data = []
  263. def insert(self, index, item):
  264. self.data.insert(index, item)
  265. lst = List()
  266. self.module.insort_left(lst, 10)
  267. self.module.insort_right(lst, 5)
  268. self.assertEqual([5, 10], lst.data)
  269. class TestInsortPython(TestInsort, unittest.TestCase):
  270. module = py_bisect
  271. class TestInsortC(TestInsort, unittest.TestCase):
  272. module = c_bisect
  273. #==============================================================================
  274. class LenOnly:
  275. "Dummy sequence class defining __len__ but not __getitem__."
  276. def __len__(self):
  277. return 10
  278. class GetOnly:
  279. "Dummy sequence class defining __getitem__ but not __len__."
  280. def __getitem__(self, ndx):
  281. return 10
  282. class CmpErr:
  283. "Dummy element that always raises an error during comparison"
  284. def __lt__(self, other):
  285. raise ZeroDivisionError
  286. __gt__ = __lt__
  287. __le__ = __lt__
  288. __ge__ = __lt__
  289. __eq__ = __lt__
  290. __ne__ = __lt__
  291. class TestErrorHandling:
  292. def test_non_sequence(self):
  293. for f in (self.module.bisect_left, self.module.bisect_right,
  294. self.module.insort_left, self.module.insort_right):
  295. self.assertRaises(TypeError, f, 10, 10)
  296. def test_len_only(self):
  297. for f in (self.module.bisect_left, self.module.bisect_right,
  298. self.module.insort_left, self.module.insort_right):
  299. self.assertRaises(TypeError, f, LenOnly(), 10)
  300. def test_get_only(self):
  301. for f in (self.module.bisect_left, self.module.bisect_right,
  302. self.module.insort_left, self.module.insort_right):
  303. self.assertRaises(TypeError, f, GetOnly(), 10)
  304. def test_cmp_err(self):
  305. seq = [CmpErr(), CmpErr(), CmpErr()]
  306. for f in (self.module.bisect_left, self.module.bisect_right,
  307. self.module.insort_left, self.module.insort_right):
  308. self.assertRaises(ZeroDivisionError, f, seq, 10)
  309. def test_arg_parsing(self):
  310. for f in (self.module.bisect_left, self.module.bisect_right,
  311. self.module.insort_left, self.module.insort_right):
  312. self.assertRaises(TypeError, f, 10)
  313. class TestErrorHandlingPython(TestErrorHandling, unittest.TestCase):
  314. module = py_bisect
  315. class TestErrorHandlingC(TestErrorHandling, unittest.TestCase):
  316. module = c_bisect
  317. #==============================================================================
  318. class TestDocExample:
  319. def test_grades(self):
  320. def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
  321. i = self.module.bisect(breakpoints, score)
  322. return grades[i]
  323. result = [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
  324. self.assertEqual(result, ['F', 'A', 'C', 'C', 'B', 'A', 'A'])
  325. def test_colors(self):
  326. data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
  327. data.sort(key=lambda r: r[1])
  328. keys = [r[1] for r in data]
  329. bisect_left = self.module.bisect_left
  330. self.assertEqual(data[bisect_left(keys, 0)], ('black', 0))
  331. self.assertEqual(data[bisect_left(keys, 1)], ('blue', 1))
  332. self.assertEqual(data[bisect_left(keys, 5)], ('red', 5))
  333. self.assertEqual(data[bisect_left(keys, 8)], ('yellow', 8))
  334. class TestDocExamplePython(TestDocExample, unittest.TestCase):
  335. module = py_bisect
  336. class TestDocExampleC(TestDocExample, unittest.TestCase):
  337. module = c_bisect
  338. #------------------------------------------------------------------------------
  339. if __name__ == "__main__":
  340. unittest.main()