MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / query

Function query

data_structures/arrays/sparse_table.py:61–88  ·  view source on GitHub ↗

>>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 0, 4) 0 >>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 4, 6) 3 >>> query(build_sparse_table([3, 1, 9]), 2, 2) 9 >>> query(build_sparse_table([3, 1, 9]), 0, 1) 1 >>> query(build_sparse_table([8, 1, 0, 3, 4

(sparse_table: list[list[int]], left_bound: int, right_bound: int)

Source from the content-addressed store, hash-verified

59
60
61def query(sparse_table: list[list[int]], left_bound: int, right_bound: int) -> int:
62 """
63 >>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 0, 4)
64 0
65 >>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 4, 6)
66 3
67 >>> query(build_sparse_table([3, 1, 9]), 2, 2)
68 9
69 >>> query(build_sparse_table([3, 1, 9]), 0, 1)
70 1
71 >>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 0, 11)
72 Traceback (most recent call last):
73 ...
74 IndexError: list index out of range
75 >>> query(build_sparse_table([]), 0, 0)
76 Traceback (most recent call last):
77 ...
78 ValueError: empty number list not allowed
79 """
80 if left_bound < 0 or right_bound >= len(sparse_table[0]):
81 raise IndexError("list index out of range")
82
83 # highest subset length of power of 2 that is within range [left_bound, right_bound]
84 j = int(log2(right_bound - left_bound + 1))
85
86 # minimum of 2 overlapping smaller subsets:
87 # [left_bound, left_bound + 2 ** j - 1] and [right_bound - 2 ** j + 1, right_bound]
88 return min(sparse_table[j][right_bound - (1 << j) + 1], sparse_table[j][left_bound])
89
90
91if __name__ == "__main__":

Callers 1

sparse_table.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected