def kth_quantiles(A, B, k, p, r): if k > 0: n = r - p + 1 location = math.floor(k / 2) * math.ceil(n / k) B[math.floor(k / 2)]= randomized_select(A, p, r, location) kth_quantiles(A, B, p, math.floor(k / 2) - 1, location - 1) kth_quantiles(A, B, math.floor(k / 2), location + 1, r)
def kth_quantiles(A, B, k, p, r): if k > 0: n = r - p + 1 location = math.floor(k / 2) * math.ceil(n / k) B[math.floor(k / 2)] = randomized_select(A, p, r, location) kth_quantiles(A, B, p, math.floor(k / 2) - 1, location - 1) kth_quantiles(A, B, math.floor(k / 2), location + 1, r)
def test_randomized_select(self): n = randint(1, 30) i = randint(1, n) A = [randint(-100, 100) for _ in range(n)] B = A.copy() for _ in range(i - 1): A.remove(min(A)) expected = min(A) actual = randomized_select(B, 0, len(B) - 1, i) self.assertEqual(expected, actual)
def run(mode, n, k): array = [] if mode == "-r": array = random_data(n) else: array = permutation(n) array_copy = array.copy() print("Tablica: {}".format(array)) print("Randomized select:") el = randomized_select(array, 0, n - 1, k) for num in array: if num == el: print("[{}]".format(num), end=" ") else: print(num, end=" ") print("\nSelect:") el = select(array_copy, k) for num in array_copy: if num == el: print("[{}]".format(num), end=" ") else: print(num, end=" ") print()
def test_randomize_select_duplicate(self): a = [10, 11, 5, 8, 2, 6, 8, 8, 100, 50] self.assertEquals(randomized_select(a, 0, 9, 4), 8) self.assertEquals(randomized_select(a, 0, 9, 5), 8) self.assertEquals(randomized_select(a, 0, 9, 6), 8)
def test_randomize_select_distinct(self): a = [10, 11, 5, 3, 2, 6, 0, 8, 100, 50] self.assertEquals(randomized_select(a, 0, 9, 5), 6)
def test_randomize_select_duplicate(self): a = [10, 11, 5, 8, 2, 6, 8, 8, 100, 50] self.assertEqual(randomized_select(a, 0, 9, 4), 8) self.assertEqual(randomized_select(a, 0, 9, 5), 8) self.assertEqual(randomized_select(a, 0, 9, 6), 8)
def test_randomize_select_distinct(self): a = [10, 11, 5, 3, 2, 6, 0, 8, 100, 50] self.assertEqual(randomized_select(a, 0, 9, 5), 6)