function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def __init__(self) -> None: self.data: list[Any] = [] self.head: int = 0 self.tail: int = 0
data_structures
def is_empty(self) -> bool: return self.head == self.tail
data_structures
def push(self, data: Any) -> None: self.data.append(data) self.tail = self.tail + 1
data_structures
def pop(self) -> Any: ret = self.data[self.head] self.head = self.head + 1 return ret
data_structures
def count(self) -> int: return self.tail - self.head
data_structures
def print_queue(self) -> None: print(self.data) print("**************") print(self.data[self.head : self.tail])
data_structures
def __init__(self, data: Any) -> None: self.data = data self.left: MyNode | None = None self.right: MyNode | None = None self.height: int = 1
data_structures
def get_data(self) -> Any: return self.data
data_structures
def get_left(self) -> MyNode | None: return self.left
data_structures
def get_right(self) -> MyNode | None: return self.right
data_structures
def get_height(self) -> int: return self.height
data_structures
def set_data(self, data: Any) -> None: self.data = data return
data_structures
def set_left(self, node: MyNode | None) -> None: self.left = node return
data_structures
def set_right(self, node: MyNode | None) -> None: self.right = node return
data_structures
def set_height(self, height: int) -> None: self.height = height return
data_structures
def get_height(node: MyNode | None) -> int: if node is None: return 0 return node.get_height()
data_structures
def my_max(a: int, b: int) -> int: if a > b: return a return b
data_structures
def right_rotation(node: MyNode) -> MyNode: print("left rotation node:", node.get_data()) ret = node.get_left() assert ret is not None node.set_left(ret.get_right()) ret.set_right(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret
data_structures
def left_rotation(node: MyNode) -> MyNode: print("right rotation node:", node.get_data()) ret = node.get_right() assert ret is not None node.set_right(ret.get_left()) ret.set_left(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret
data_structures
def lr_rotation(node: MyNode) -> MyNode: left_child = node.get_left() assert left_child is not None node.set_left(left_rotation(left_child)) return right_rotation(node)
data_structures
def rl_rotation(node: MyNode) -> MyNode: right_child = node.get_right() assert right_child is not None node.set_right(right_rotation(right_child)) return left_rotation(node)
data_structures
def insert_node(node: MyNode | None, data: Any) -> MyNode | None: if node is None: return MyNode(data) if data < node.get_data(): node.set_left(insert_node(node.get_left(), data)) if ( get_height(node.get_left()) - get_height(node.get_right()) == 2 ): # an unbalance detected left_child = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child node = right_rotation(node) else: node = lr_rotation(node) else: node.set_right(insert_node(node.get_right(), data)) if get_height(node.get_right()) - get_height(node.get_left()) == 2: right_child = node.get_right() assert right_child is not None if data < right_child.get_data(): node = rl_rotation(node) else: node = left_rotation(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) return node
data_structures
def get_right_most(root: MyNode) -> Any: while True: right_child = root.get_right() if right_child is None: break root = right_child return root.get_data()
data_structures
def get_left_most(root: MyNode) -> Any: while True: left_child = root.get_left() if left_child is None: break root = left_child return root.get_data()
data_structures
def del_node(root: MyNode, data: Any) -> MyNode | None: left_child = root.get_left() right_child = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: temp_data = get_left_most(right_child) root.set_data(temp_data) root.set_right(del_node(right_child, temp_data)) elif left_child is not None: root = left_child elif right_child is not None: root = right_child else: return None elif root.get_data() > data: if left_child is None: print("No such data") return root else: root.set_left(del_node(left_child, data)) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(right_child, data)) if get_height(right_child) - get_height(left_child) == 2: assert right_child is not None if get_height(right_child.get_right()) > get_height(right_child.get_left()): root = left_rotation(root) else: root = rl_rotation(root) elif get_height(right_child) - get_height(left_child) == -2: assert left_child is not None if get_height(left_child.get_left()) > get_height(left_child.get_right()): root = right_rotation(root) else: root = lr_rotation(root) height = my_max(get_height(root.get_right()), get_height(root.get_left())) + 1 root.set_height(height) return root
data_structures
def __init__(self) -> None: self.root: MyNode | None = None
data_structures
def get_height(self) -> int: return get_height(self.root)
data_structures
def insert(self, data: Any) -> None: print("insert:" + str(data)) self.root = insert_node(self.root, data)
data_structures
def del_node(self, data: Any) -> None: print("delete:" + str(data)) if self.root is None: print("Tree is empty!") return self.root = del_node(self.root, data)
data_structures
def __str__( self, ) -> str: # a level traversale, gives a more intuitive look on the tree output = "" q = MyQueue() q.push(self.root) layer = self.get_height() if layer == 0: return output cnt = 0 while not q.is_empty(): node = q.pop() space = " " * int(math.pow(2, layer - 1)) output += space if node is None: output += "*" q.push(None) q.push(None) else: output += str(node.get_data()) q.push(node.get_left()) q.push(node.get_right()) output += space cnt = cnt + 1 for i in range(100): if cnt == math.pow(2, i) - 1: layer = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output
data_structures
def _test() -> None: import doctest doctest.testmod()
data_structures
def __init__(self, value: int | None = None): self.value = value self.prior = random() self.left: Node | None = None self.right: Node | None = None
data_structures
def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.value}: {self.prior:.5}'" else: return pformat( {f"{self.value}: {self.prior:.5}": (self.left, self.right)}, indent=1 )
data_structures
def __str__(self) -> str: value = str(self.value) + " " left = str(self.left or "") right = str(self.right or "") return value + left + right
data_structures
def split(root: Node | None, value: int) -> tuple[Node | None, Node | None]: if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: left, root.left = split(root.left, value) return left, root else: root.right, right = split(root.right, value) return root, right
data_structures
def merge(left: Node | None, right: Node | None) -> Node | None: if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: left.right = merge(left.right, right) return left else: right.left = merge(left, right.left) return right
data_structures
def insert(root: Node | None, value: int) -> Node | None: node = Node(value) left, right = split(root, value) return merge(merge(left, node), right)
data_structures
def erase(root: Node | None, value: int) -> Node | None: left, right = split(root, value - 1) _, right = split(right, value) return merge(left, right)
data_structures
def inorder(root: Node | None) -> None: if not root: # None return else: inorder(root.left) print(root.value, end=",") inorder(root.right)
data_structures
def interact_treap(root: Node | None, args: str) -> Node | None: for arg in args.split(): if arg[0] == "+": root = insert(root, int(arg[1:])) elif arg[0] == "-": root = erase(root, int(arg[1:])) else: print("Unknown command") return root
data_structures
def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None: any_type: Any | T = None self.N: int = len(arr) self.st: list[T] = [any_type for _ in range(self.N)] + arr self.fn = fnc self.build()
data_structures
def build(self) -> None: for p in range(self.N - 1, 0, -1): self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1])
data_structures
def update(self, p: int, v: T) -> None: p += self.N self.st[p] = v while p > 1: p = p // 2 self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1])
data_structures
def query(self, l: int, r: int) -> T | None: # noqa: E741 l, r = l + self.N, r + self.N res: T | None = None while l <= r: if l % 2 == 1: res = self.st[l] if res is None else self.fn(res, self.st[l]) if r % 2 == 0: res = self.st[r] if res is None else self.fn(res, self.st[r]) l, r = (l + 1) // 2, (r - 1) // 2 return res
data_structures
def test_all_segments() -> None: for i in range(len(test_array)): for j in range(i, len(test_array)): min_range = reduce(min, test_array[i : j + 1]) max_range = reduce(max, test_array[i : j + 1]) sum_range = reduce(lambda a, b: a + b, test_array[i : j + 1]) assert min_range == min_segment_tree.query(i, j) assert max_range == max_segment_tree.query(i, j) assert sum_range == sum_segment_tree.query(i, j)
data_structures
def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end self.val = val self.mid = (start + end) // 2 self.left = left self.right = right
data_structures
def __repr__(self): return f"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})"
data_structures
def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1)
data_structures
def update(self, i, val): self._update_tree(self.root, i, val)
data_structures
def query_range(self, i, j): return self._query_range(self.root, i, j)
data_structures
def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right)
data_structures
def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val)
data_structures
def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j)
data_structures
def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right)
data_structures
def __init__(self, arr: list[int] | None = None, size: int | None = None) -> None: if arr is None and size is not None: self.size = size self.tree = [0] * size elif arr is not None: self.init(arr) else: raise ValueError("Either arr or size must be specified")
data_structures
def init(self, arr: list[int]) -> None: self.size = len(arr) self.tree = deepcopy(arr) for i in range(1, self.size): j = self.next_(i) if j < self.size: self.tree[j] += self.tree[i]
data_structures
def get_array(self) -> list[int]: arr = self.tree[:] for i in range(self.size - 1, 0, -1): j = self.next_(i) if j < self.size: arr[j] -= arr[i] return arr
data_structures
def next_(index: int) -> int: return index + (index & (-index))
data_structures
def prev(index: int) -> int: return index - (index & (-index))
data_structures
def add(self, index: int, value: int) -> None: if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value index = self.next_(index)
data_structures
def update(self, index: int, value: int) -> None: self.add(index, value - self.get(index))
data_structures
def prefix(self, right: int) -> int: if right == 0: return 0 result = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] right = self.prev(right) return result
data_structures
def query(self, left: int, right: int) -> int: return self.prefix(right) - self.prefix(left)
data_structures
def get(self, index: int) -> int: return self.query(index, index + 1)
data_structures
def rank_query(self, value: int) -> int: value -= self.tree[0] if value < 0: return -1 j = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 i = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i
data_structures
def __init__(self, value: int | None = None): self.value = value self.parent: Node | None = None # Added in order to delete a node easier self.left: Node | None = None self.right: Node | None = None
data_structures
def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return str(self.value) return pformat({f"{self.value}": (self.left, self.right)}, indent=1)
data_structures
def __init__(self, root: Node | None = None): self.root = root
data_structures
def __str__(self) -> str: return str(self.root)
data_structures
def __reassign_nodes(self, node: Node, new_children: Node | None) -> None: if new_children is not None: # reset its kids new_children.parent = node.parent if node.parent is not None: # reset its parent if self.is_right(node): # If it is the right children node.parent.right = new_children else: node.parent.left = new_children else: self.root = None
data_structures
def is_right(self, node: Node) -> bool: if node.parent and node.parent.right: return node == node.parent.right return False
data_structures
def empty(self) -> bool: return self.root is None
data_structures
def __insert(self, value) -> None: new_node = Node(value) # create a new Node if self.empty(): # if Tree is empty self.root = new_node # set its root else: # Tree is not empty parent_node = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: parent_node.left = new_node # We insert the new node in a leaf break else: parent_node = parent_node.left else: if parent_node.right is None: parent_node.right = new_node break else: parent_node = parent_node.right new_node.parent = parent_node
data_structures
def insert(self, *values) -> None: for value in values: self.__insert(value)
data_structures
def search(self, value) -> Node | None: if self.empty(): raise IndexError("Warning: Tree is empty! please use another.") else: node = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: node = node.left if value < node.value else node.right return node
data_structures
def get_max(self, node: Node | None = None) -> Node | None: if node is None: if self.root is None: return None node = self.root if not self.empty(): while node.right is not None: node = node.right return node
data_structures
def get_min(self, node: Node | None = None) -> Node | None: if node is None: node = self.root if self.root is None: return None if not self.empty(): node = self.root while node.left is not None: node = node.left return node
data_structures
def remove(self, value: int) -> None: node = self.search(value) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(node, None) elif node.left is None: # Has only right children self.__reassign_nodes(node, node.right) elif node.right is None: # Has only left children self.__reassign_nodes(node, node.left) else: tmp_node = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value) # type: ignore node.value = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure
data_structures
def preorder_traverse(self, node: Node | None) -> Iterable: if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left) yield from self.preorder_traverse(node.right)
data_structures
def traversal_tree(self, traversal_function=None) -> Any: if traversal_function is None: return self.preorder_traverse(self.root) else: return traversal_function(self.root)
data_structures
def inorder(self, arr: list, node: Node | None) -> None: if node: self.inorder(arr, node.left) arr.append(node.value) self.inorder(arr, node.right)
data_structures
def find_kth_smallest(self, k: int, node: Node) -> int:
data_structures
def make_tree() -> Node | None: tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) return tree
data_structures
def preorder(root: Node | None) -> list[int]: return [root.data, *preorder(root.left), *preorder(root.right)] if root else []
data_structures
def postorder(root: Node | None) -> list[int]: return postorder(root.left) + postorder(root.right) + [root.data] if root else []
data_structures
def inorder(root: Node | None) -> list[int]: return [*inorder(root.left), root.data, *inorder(root.right)] if root else []
data_structures
def height(root: Node | None) -> int: return (max(height(root.left), height(root.right)) + 1) if root else 0
data_structures
def level_order(root: Node | None) -> Sequence[Node | None]: output: list[Any] = [] if root is None: return output process_queue = deque([root]) while process_queue: node = process_queue.popleft() output.append(node.data) if node.left: process_queue.append(node.left) if node.right: process_queue.append(node.right) return output
data_structures
def populate_output(root: Node | None, level: int) -> None: if not root: return if level == 1: output.append(root.data) elif level > 1: populate_output(root.left, level - 1) populate_output(root.right, level - 1)
data_structures
def populate_output(root: Node | None, level: int) -> None: if root is None: return if level == 1: output.append(root.data) elif level > 1: populate_output(root.right, level - 1) populate_output(root.left, level - 1)
data_structures
def zigzag(root: Node | None) -> Sequence[Node | None] | list[Any]: if root is None: return [] output: list[Sequence[Node | None]] = [] flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if not flag: output.append(get_nodes_from_left_to_right(root, h)) flag = 1 else: output.append(get_nodes_from_right_to_left(root, h)) flag = 0 return output
data_structures
def main() -> None: # Main function for testing. root = make_tree() print(f"In-order Traversal: {inorder(root)}") print(f"Pre-order Traversal: {preorder(root)}") print(f"Post-order Traversal: {postorder(root)}", "\n") print(f"Height of Tree: {height(root)}", "\n") print("Complete Level Order Traversal: ") print(level_order(root), "\n") print("Level-wise order Traversal: ") for level in range(1, height(root) + 1): print(f"Level {level}:", get_nodes_from_left_to_right(root, level=level)) print("\nZigZag order Traversal: ") print(zigzag(root))
data_structures
def __init__( self, label: int | None = None, color: int = 0, parent: RedBlackTree | None = None, left: RedBlackTree | None = None, right: RedBlackTree | None = None, ) -> None: self.label = label self.parent = parent self.left = left self.right = right self.color = color
data_structures
def rotate_left(self) -> RedBlackTree: parent = self.parent right = self.right if right is None: return self self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right
data_structures
def rotate_right(self) -> RedBlackTree: if self.left is None: return self parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left
data_structures
def insert(self, label: int) -> RedBlackTree: if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self
data_structures
def _insert_repair(self) -> None: if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() if value is not None: self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.parent: if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label is not None and self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self
data_structures
def _remove_repair(self) -> None: is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. Red-Black Tree. See check_color_properties for more info. leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). found somewhere in the tree. Guaranteed to run in O(log(n)) time. it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. This method is guaranteed to run in O(log(n)) time. This method is guaranteed to run in O(log(n)) time. This method is guaranteed to run in O(log(n)) time. if self.parent is None: return None else: return self.parent.parent
data_structures
def sibling(self) -> RedBlackTree | None: if self.parent is None: return False return self.parent.left is self.parent.left is self
data_structures
def is_right(self) -> bool: Return the number of nodes in this tree. if not isinstance(other, RedBlackTree): return NotImplemented if self.label == other.label: return self.left == other.left and self.right == other.right else: return False
data_structures