|
| 1 | +import math |
| 2 | + |
| 3 | +from hypothesis import given |
| 4 | +from hypothesis import strategies as st |
| 5 | +from hypothesis.strategies import integers |
| 6 | +from hypothesis.strategies import just |
| 7 | +from hypothesis.strategies import lists |
| 8 | + |
| 9 | +from solutions.chapter7.section1.exercise2 import fair_partition |
| 10 | +from test_case import ClrsTestCase |
| 11 | +from test_util import create_array |
| 12 | +from util import range_of |
| 13 | + |
| 14 | + |
| 15 | +class TestChapter7(ClrsTestCase): |
| 16 | + |
| 17 | + @given(st.data()) |
| 18 | + def test_fair_partition(self, data): |
| 19 | + elements = data.draw(lists(integers(), min_size=1)) |
| 20 | + A = create_array(elements) |
| 21 | + n = len(elements) |
| 22 | + |
| 23 | + actual_split_index = fair_partition(A, 1, n) |
| 24 | + |
| 25 | + left_max = -math.inf |
| 26 | + right_min = math.inf |
| 27 | + for i in range_of(1, to=actual_split_index): |
| 28 | + left_max = max(left_max, A[i]) |
| 29 | + for i in range_of(actual_split_index + 1, to=n): |
| 30 | + right_min = min(right_min, A[i]) |
| 31 | + self.assertLessEqual(left_max, right_min) |
| 32 | + self.assertArrayPermuted(A, elements, end=n) |
| 33 | + |
| 34 | + @given(st.data()) |
| 35 | + def test_fair_partition_all_values_equal(self, data): |
| 36 | + value = data.draw(integers()) |
| 37 | + elements = data.draw(lists(just(value), min_size=1)) |
| 38 | + A = create_array(elements) |
| 39 | + n = len(elements) |
| 40 | + |
| 41 | + actual_split_index = fair_partition(A, 1, n) |
| 42 | + |
| 43 | + self.assertEqual(actual_split_index, (n + 1) // 2) |
0 commit comments