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

Function quantile

data_structures/binary_tree/wavelet_tree.py:121–158  ·  view source on GitHub ↗

Returns the index'th smallest element in interval [start, end] in the list index is 0-indexed >>> root = build_tree(test_array) >>> quantile(root, 2, 2, 5) 5 >>> quantile(root, 5, 2, 13) 4 >>> quantile(root, 0, 6, 6) 8 >>> quantile(root, 4, 2, 5) -1

(node: Node | None, index: int, start: int, end: int)

Source from the content-addressed store, hash-verified

119
120
121def quantile(node: Node | None, index: int, start: int, end: int) -> int:
122 """
123 Returns the index'th smallest element in interval [start, end] in the list
124 index is 0-indexed
125
126 >>> root = build_tree(test_array)
127 >>> quantile(root, 2, 2, 5)
128 5
129 >>> quantile(root, 5, 2, 13)
130 4
131 >>> quantile(root, 0, 6, 6)
132 8
133 >>> quantile(root, 4, 2, 5)
134 -1
135 """
136 if index > (end - start) or start > end or node is None:
137 return -1
138 # Leaf node case
139 if node.minn == node.maxx:
140 return node.minn
141 # Number of elements in the left subtree in interval [start, end]
142 num_elements_in_left_tree = node.map_left[end] - (
143 node.map_left[start - 1] if start else 0
144 )
145 if num_elements_in_left_tree > index:
146 return quantile(
147 node.left,
148 index,
149 (node.map_left[start - 1] if start else 0),
150 node.map_left[end] - 1,
151 )
152 else:
153 return quantile(
154 node.right,
155 index - num_elements_in_left_tree,
156 start - (node.map_left[start - 1] if start else 0),
157 end - node.map_left[end],
158 )
159
160
161def range_counting(

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected