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_node to head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node
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 = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next return delete_node.data
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 current node prev = current # Make the current node the next node (to progress iteration) current = next_node # Return prev in order to put the head at the end self.head = prev
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. try: linked_list.delete_tail() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True for i in range(0, 9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(0, 9)) is True linked_list.reverse() assert str(linked_list) == "->".join(str(i) for i in range(-8, 1))
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 = LinkedList() for i in test_input: linked_list.insert_tail(i) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(linked_list) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head result = linked_list.delete_head() assert result == -9 assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail result = linked_list.delete_tail() assert result == 12.2 assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list result = linked_list.delete_nth(10) assert result is None assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!")) assert ( str(linked_list) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(None) assert ( str(linked_list) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(linked_list) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" )
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("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}")
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.charge_factor = 1 if charge_factor is None else charge_factor self.__aux_list: list = [] self._keys: dict = {}
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 = None break return 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: self.insert_data(value)
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 self._len = 0
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 True else: return False
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 numbers are not primes return False odd_numbers = range(3, int(math.sqrt(number) + 1), 2) return not any(not number % i for i in odd_numbers)
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_exc) == str(py_exc) assert set(py) == set(my) assert len(py) == len(my) assert set(my.items()) == set(py.items())
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 from the current node to a new one # containing the word elif word[0] not in self.nodes: self.nodes[word[0]] = RadixNode(prefix=word, is_leaf=True) else: incoming_node = self.nodes[word[0]] matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(remaining_word) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: incoming_node.prefix = remaining_prefix aux_node = self.nodes[matching_string[0]] self.nodes[matching_string[0]] = RadixNode(matching_string, False) self.nodes[matching_string[0]].nodes[remaining_prefix[0]] = aux_node if remaining_word == "": self.nodes[matching_string[0]].is_leaf = True else: self.nodes[matching_string[0]].insert(remaining_word)
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, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(remaining_word)
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 prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(remaining_word) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes) == 1 and not self.is_leaf: merging_node = list(self.nodes.values())[0] self.is_leaf = merging_node.is_leaf self.prefix += merging_node.prefix self.nodes = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes) > 1: incoming_node.is_leaf = False # If there is 1 edge, we merge it with its child else: merging_node = list(incoming_node.nodes.values())[0] incoming_node.is_leaf = merging_node.is_leaf incoming_node.prefix += merging_node.prefix incoming_node.nodes = merging_node.nodes return True
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") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True
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] char_node = curr.nodes.get(char) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted delete_curr = _delete(char_node, word, index + 1) if delete_curr: del curr.nodes[char] return len(curr.nodes) == 0 return delete_curr
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") assert root.find("apple") assert root.find("all") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True
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) return 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] < array[smallest]: smallest = r if smallest != idx: array[idx], array[smallest] = array[smallest], array[idx] ( self.idx_of_element[array[idx]], self.idx_of_element[array[smallest]], ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) idx = smallest else: break
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.heap[idx]], self.idx_of_element[self.heap[p]], ) idx = p p = self.get_parent_idx(idx)
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_of_element[x] self.sift_down(0, self.heap) return x
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. self.h = list(collection) self.heap_size = len(self.h) if self.heap_size > 1: # max_heapify from right to left but exclude leaves (last level) for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i)
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 to evaluate the score of an item on which basis ordering # will be done. self.key = key or (lambda x: x)
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. self.arr[i], self.arr[j] = self.arr[j], self.arr[i]
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 = parent, self._parent(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. self._heapify_up(index) self._heapify_down(index)
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._heapify_up(self.size - 1)
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(temp, root2) return result
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