function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def insert_tail(self, data: Any) -> None: self.insert_nth(len(self), data)
data_structures
def insert_head(self, data: Any) -> None: self.insert_nth(0, data)
data_structures
def insert_nth(self, index: int, data: Any) -> None: if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next = self.head # link new_nod...
data_structures
def print_list(self) -> None: # print every node data print(self)
data_structures
def delete_head(self) -> Any: return self.delete_nth(0)
data_structures
def delete_tail(self) -> Any: # delete from tail return self.delete_nth(len(self) - 1)
data_structures
def delete_nth(self, index: int = 0) -> Any: if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("List index out of range.") delete_node = self.head # default first node if index == 0: self.head = self.head.next else: temp =...
data_structures
def is_empty(self) -> bool: return self.head is None
data_structures
def reverse(self) -> None: prev = None current = self.head while current: # Store the current node's next node. next_node = current.next # Make the current node's next point backwards current.next = prev # Make the previous node be the...
data_structures
def test_singly_linked_list() -> None: linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. t...
data_structures
def test_singly_linked_list_2() -> None: test_input = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.55555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] linked_list = LinkedLi...
data_structures
def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("...
data_structures
def __init__( self, size_table: int, charge_factor: int | None = None, lim_charge: float | None = None, ) -> None: self.size_table = size_table self.values = [None] * self.size_table self.lim_charge = 0.75 if lim_charge is None else lim_charge self.cha...
data_structures
def keys(self): return self._keys
data_structures
def balanced_factor(self): return sum(1 for slot in self.values if slot is not None) / ( self.size_table * self.charge_factor )
data_structures
def hash_function(self, key): return key % self.size_table
data_structures
def _step_by_step(self, step_ord): print(f"step {step_ord}") print(list(range(len(self.values)))) print(self.values)
data_structures
def bulk_insert(self, values): i = 1 self.__aux_list = values for value in values: self.insert_data(value) self._step_by_step(i) i += 1
data_structures
def _set_value(self, key, data): self.values[key] = data self._keys[key] = data
data_structures
def _collision_resolution(self, key, data=None): new_key = self.hash_function(key + 1) while self.values[new_key] is not None and self.values[new_key] != key: if self.values.count(None) > 0: new_key = self.hash_function(new_key + 1) else: new_key ...
data_structures
def rehashing(self): survivor_values = [value for value in self.values if value is not None] self.size_table = next_prime(self.size_table, factor=2) self._keys.clear() self.values = [None] * self.size_table # hell's pointers D: don't DRY ;/ for value in survivor_values: ...
data_structures
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
data_structures
def __hash_function_2(self, value, data): next_prime_gt = ( next_prime(value % self.size_table) if not is_prime(value % self.size_table) else value % self.size_table ) # gt = bigger than return next_prime_gt - (data % next_prime_gt)
data_structures
def __hash_double_function(self, key, data, increment): return (increment * self.__hash_function_2(key, data)) % self.size_table
data_structures
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
data_structures
def _set_value(self, key, data): self.values[key] = deque([]) if self.values[key] is None else self.values[key] self.values[key].appendleft(data) self._keys[key] = self.values[key]
data_structures
def balanced_factor(self): return ( sum(self.charge_factor - len(slot) for slot in self.values) / self.size_table * self.charge_factor )
data_structures
def __init__(self) -> None: super().__init__(None, None)
data_structures
def __bool__(self) -> bool: return False
data_structures
def __init__( self, initial_block_size: int = 8, capacity_factor: float = 0.75 ) -> None: self._initial_block_size = initial_block_size self._buckets: list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 self._capacity_factor = capacity_factor ...
data_structures
def _get_bucket_index(self, key: KEY) -> int: return hash(key) % len(self._buckets)
data_structures
def _get_next_ind(self, ind: int) -> int: return (ind + 1) % len(self._buckets)
data_structures
def _try_set(self, ind: int, key: KEY, val: VAL) -> bool: stored = self._buckets[ind] if not stored: self._buckets[ind] = _Item(key, val) self._len += 1 return True elif stored.key == key: self._buckets[ind] = _Item(key, val) return Tru...
data_structures
def _is_full(self) -> bool: limit = len(self._buckets) * self._capacity_factor return len(self) >= int(limit)
data_structures
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
data_structures
def is_prime(number: int) -> bool: # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbe...
data_structures
def _get(k): return getitem, k
data_structures
def _set(k, v): return setitem, k, v
data_structures
def _del(k): return delitem, k
data_structures
def _run_operation(obj, fun, *args): try: return fun(obj, *args), None except Exception as e: return None, e
data_structures
def test_hash_map_is_the_same_as_dict(operations): my = HashMap(initial_block_size=4) py = {} for _, (fun, *args) in enumerate(operations): my_res, my_exc = _run_operation(my, fun, *args) py_res, py_exc = _run_operation(py, fun, *args) assert my_res == py_res assert str(my_ex...
data_structures
def is_public(name: str) -> bool: return not name.startswith("_")
data_structures
def __init__(self, prefix: str = "", is_leaf: bool = False) -> None: # Mapping from the first character of the prefix of the node self.nodes: dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word self.is_leaf = is_leaf self.prefix = prefix
data_structures
def match(self, word: str) -> tuple[str, str, str]: x = 0 for q, w in zip(self.prefix, word): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:]
data_structures
def insert_many(self, words: list[str]) -> None: for word in words: self.insert(word)
data_structures
def insert(self, word: str) -> None: # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word: self.is_leaf = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge f...
data_structures
def find(self, word: str) -> bool: incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # If there is remaining prefix...
data_structures
def delete(self, word: str) -> bool: incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # If there is remaining pref...
data_structures
def print_tree(self, height: int = 0) -> None: if self.prefix != "": print("-" * height, self.prefix, " (leaf)" if self.is_leaf else "") for value in self.nodes.values(): value.print_tree(height + 1)
data_structures
def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = RadixNode() root.insert_many(words) assert all(root.find(word) for word in words) assert not root.find("bandanas") assert not root.find("apps") root.delete("all") assert not root.find("all") ...
data_structures
def pytests() -> None: assert test_trie()
data_structures
def main() -> None: root = RadixNode() words = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(words) print("Words:", words) print("Tree:") root.print_tree()
data_structures
def __init__(self) -> None: self.nodes: dict[str, TrieNode] = {} # Mapping from char to TrieNode self.is_leaf = False
data_structures
def insert_many(self, words: list[str]) -> None: for word in words: self.insert(word)
data_structures
def insert(self, word: str) -> None: curr = self for char in word: if char not in curr.nodes: curr.nodes[char] = TrieNode() curr = curr.nodes[char] curr.is_leaf = True
data_structures
def find(self, word: str) -> bool: curr = self for char in word: if char not in curr.nodes: return False curr = curr.nodes[char] return curr.is_leaf
data_structures
def _delete(curr: TrieNode, word: str, index: int) -> bool: if index == len(word): # If word does not exist if not curr.is_leaf: return False curr.is_leaf = False return len(curr.nodes) == 0 char = word[index] ...
data_structures
def print_words(node: TrieNode, word: str) -> None: if node.is_leaf: print(word, end=" ") for key, value in node.nodes.items(): print_words(value, word + key)
data_structures
def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = TrieNode() root.insert_many(words) # print_words(root, "") assert all(root.find(word) for word in words) assert root.find("banana") assert not root.find("bandanas") assert not root.find("apps") ...
data_structures
def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(")
data_structures
def pytests() -> None: assert test_trie()
data_structures
def main() -> None: print_results("Testing trie functionality", test_trie())
data_structures
def __init__(self, name, val): self.name = name self.val = val
data_structures
def __str__(self): return f"{self.__class__.__name__}({self.name}, {self.val})"
data_structures
def __lt__(self, other): return self.val < other.val
data_structures
def __init__(self, array): self.idx_of_element = {} self.heap_dict = {} self.heap = self.build_heap(array)
data_structures
def __getitem__(self, key): return self.get_value(key)
data_structures
def get_parent_idx(self, idx): return (idx - 1) // 2
data_structures
def get_left_child_idx(self, idx): return idx * 2 + 1
data_structures
def get_right_child_idx(self, idx): return idx * 2 + 2
data_structures
def get_value(self, key): return self.heap_dict[key]
data_structures
def build_heap(self, array): last_idx = len(array) - 1 start_from = self.get_parent_idx(last_idx) for idx, i in enumerate(array): self.idx_of_element[i] = idx self.heap_dict[i.name] = i.val for i in range(start_from, -1, -1): self.sift_down(i, array)...
data_structures
def sift_down(self, idx, array): while True: l = self.get_left_child_idx(idx) # noqa: E741 r = self.get_right_child_idx(idx) smallest = idx if l < len(array) and array[l] < array[idx]: smallest = l if r < len(array) and array[r] < arr...
data_structures
def sift_up(self, idx): p = self.get_parent_idx(idx) while p >= 0 and self.heap[p] > self.heap[idx]: self.heap[p], self.heap[idx] = self.heap[idx], self.heap[p] self.idx_of_element[self.heap[p]], self.idx_of_element[self.heap[idx]] = ( self.idx_of_element[self.hea...
data_structures
def peek(self): return self.heap[0]
data_structures
def remove(self): self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0] self.idx_of_element[self.heap[0]], self.idx_of_element[self.heap[-1]] = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) x = self.heap.pop() del self.idx...
data_structures
def insert(self, node): self.heap.append(node) self.idx_of_element[node] = len(self.heap) - 1 self.heap_dict[node.name] = node.val self.sift_up(len(self.heap) - 1)
data_structures
def is_empty(self): return len(self.heap) == 0
data_structures
def decrease_key(self, node, new_value): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" node.val = new_value self.heap_dict[node.name] = new_value self.sift_up(self.idx_of_element[node])
data_structures
def __init__(self) -> None: self.h: list[float] = [] self.heap_size: int = 0
data_structures
def __repr__(self) -> str: return str(self.h)
data_structures
def parent_index(self, child_idx: int) -> int | None: return the left child index if the left child exists. if not, return None. return the right child index if the right child exists. if not, return None. correct a single violation of the heap property in a subtree's root. ...
data_structures
def extract_max(self) -> float: self.h.append(value) idx = (self.heap_size - 1) // 2 self.heap_size += 1 while idx >= 0: self.max_heapify(idx) idx = (idx - 1) // 2
data_structures
def heap_sort(self) -> None: size = self.heap_size for j in range(size - 1, 0, -1): self.h[0], self.h[j] = self.h[j], self.h[0] self.heap_size -= 1 self.max_heapify(0) self.heap_size = size
data_structures
def __init__(self, key: Callable | None = None) -> None: # Stores actual heap items. self.arr: list = [] # Stores indexes of each item for supporting updates and deletion. self.pos_map: dict = {} # Stores current size of heap. self.size = 0 # Stores function used ...
data_structures
def _parent(self, i: int) -> int | None: left = int(2 * i + 1) return left if 0 < left < self.size else None
data_structures
def _right(self, i: int) -> int | None: # First update the indexes of the items in index map. self.pos_map[self.arr[i][0]], self.pos_map[self.arr[j][0]] = ( self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]], ) # Then swap the items in the list. se...
data_structures
def _cmp(self, i: int, j: int) -> bool: Returns index of valid parent as per desired ordering among given index and both it's children parent = self._parent(index) while parent is not None and not self._cmp(index, parent): self._swap(index, parent) index, parent =...
data_structures
def _heapify_down(self, index: int) -> None: if item not in self.pos_map: return index = self.pos_map[item] self.arr[index] = [item, self.key(item_value)] # Make sure heap is right in both up and down direction. # Ideally only one of them will make any change. ...
data_structures
def delete_item(self, item: int) -> None: arr_len = len(self.arr) if arr_len == self.size: self.arr.append([item, self.key(item_value)]) else: self.arr[self.size] = [item, self.key(item_value)] self.pos_map[item] = self.size self.size += 1 self._he...
data_structures
def get_top(self) -> tuple | None: Return top item tuple (Calculated value, item) from heap and removes it as well if present
data_structures
def __init__(self, value: T) -> None: self._value: T = value self.left: SkewNode[T] | None = None self.right: SkewNode[T] | None = None
data_structures
def value(self) -> T: if not root1: return root2 if not root2: return root1 if root1.value > root2.value: root1, root2 = root2, root1 result = root1 temp = root1.right result.right = root1.left result.left = SkewNode.merge(te...
data_structures
def __init__(self, data: Iterable[T] | None = ()) -> None: self._root: SkewNode[T] | None = None if data: for item in data: self.insert(item)
data_structures
def __bool__(self) -> bool: return self._root is not None
data_structures
def __iter__(self) -> Iterator[T]: result: list[Any] = [] while self: result.append(self.pop()) # Pushing items back to the heap not to clear it. for item in result: self.insert(item) return iter(result)
data_structures
def insert(self, value: T) -> None: self._root = SkewNode.merge(self._root, SkewNode(value))
data_structures
def pop(self) -> T | None: result = self.top() self._root = ( SkewNode.merge(self._root.left, self._root.right) if self._root else None ) return result
data_structures
def top(self) -> T: if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value
data_structures
def clear(self) -> None: self._root = None
data_structures