function stringlengths 18 3.86k | intent_category stringlengths 5 24 |
|---|---|
def bfs(graph, s, t, parent):
# Return True if there is node that has not iterated.
visited = [False] * len(graph)
queue = [s]
visited[s] = True
while queue:
u = queue.pop(0)
for ind in range(len(graph[u])):
if visited[ind] is False and graph[u][ind] > 0:
... | networking_flow |
def mincut(graph, source, sink):
parent = [-1] * (len(graph))
max_flow = 0
res = []
temp = [i[:] for i in graph] # Record original cut, copy.
while bfs(graph, source, sink, parent):
path_flow = float("Inf")
s = sink
while s != source:
# Find the minimum value in... | networking_flow |
def bfs(graph, s, t, parent):
# Return True if there is node that has not iterated.
visited = [False] * len(graph)
queue = []
queue.append(s)
visited[s] = True
while queue:
u = queue.pop(0)
for ind in range(len(graph[u])):
if visited[ind] is False and graph[u][ind] >... | networking_flow |
def ford_fulkerson(graph, source, sink):
# This array is filled by BFS and to store path
parent = [-1] * (len(graph))
max_flow = 0
while bfs(graph, source, sink, parent):
path_flow = float("Inf")
s = sink
while s != source:
# Find the minimum value in select path
... | networking_flow |
def binary_search(a_list: list[int], item: int) -> bool:
if len(a_list) == 0:
return False
midpoint = len(a_list) // 2
if a_list[midpoint] == item:
return True
if item < a_list[midpoint]:
return binary_search(a_list[:midpoint], item)
else:
return binary_search(a_list[... | searches |
def simulated_annealing(
search_prob,
find_max: bool = True,
max_x: float = math.inf,
min_x: float = -math.inf,
max_y: float = math.inf,
min_y: float = -math.inf,
visualization: bool = False,
start_temperate: float = 100,
rate_of_decrease: float = 0.01,
threshold_temp: float = 1,... | searches |
def test_f1(x, y):
return (x**2) + (y**2) | searches |
def test_f2(x, y):
return (3 * x**2) - (6 * y) | searches |
def __init__(self, x: int, y: int, step_size: int, function_to_optimize):
self.x = x
self.y = y
self.step_size = step_size
self.function = function_to_optimize | searches |
def score(self) -> int:
return self.function(self.x, self.y) | searches |
def get_neighbors(self):
step_size = self.step_size
return [
SearchProblem(x, y, step_size, self.function)
for x, y in (
(self.x - step_size, self.y - step_size),
(self.x - step_size, self.y),
(self.x - step_size, self.y + step_size... | searches |
def __hash__(self):
return hash(str(self)) | searches |
def __eq__(self, obj):
if isinstance(obj, SearchProblem):
return hash(str(self)) == hash(str(obj))
return False | searches |
def __str__(self):
return f"x: {self.x} y: {self.y}" | searches |
def hill_climbing(
search_prob,
find_max: bool = True,
max_x: float = math.inf,
min_x: float = -math.inf,
max_y: float = math.inf,
min_y: float = -math.inf,
visualization: bool = False,
max_iter: int = 10000,
) -> SearchProblem:
current_state = search_prob
scores = [] # list to ... | searches |
def test_f1(x, y):
return (x**2) + (y**2) | searches |
def test_f2(x, y):
return (3 * x**2) - (6 * y) | searches |
def bisect_left(
sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1
) -> int:
if hi < 0:
hi = len(sorted_collection)
while lo < hi:
mid = lo + (hi - lo) // 2
if sorted_collection[mid] < item:
lo = mid + 1
else:
hi = mid
return lo | searches |
def bisect_right(
sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1
) -> int:
if hi < 0:
hi = len(sorted_collection)
while lo < hi:
mid = lo + (hi - lo) // 2
if sorted_collection[mid] <= item:
lo = mid + 1
else:
hi = mid
return l... | searches |
def insort_left(
sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1
) -> None:
sorted_collection.insert(bisect_left(sorted_collection, item, lo, hi), item) | searches |
def insort_right(
sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1
) -> None:
sorted_collection.insert(bisect_right(sorted_collection, item, lo, hi), item) | searches |
def binary_search(sorted_collection: list[int], item: int) -> int | None:
left = 0
right = len(sorted_collection) - 1
while left <= right:
midpoint = left + (right - left) // 2
current_item = sorted_collection[midpoint]
if current_item == item:
return midpoint
el... | searches |
def binary_search_std_lib(sorted_collection: list[int], item: int) -> int | None:
index = bisect.bisect_left(sorted_collection, item)
if index != len(sorted_collection) and sorted_collection[index] == item:
return index
return None | searches |
def binary_search_by_recursion(
sorted_collection: list[int], item: int, left: int, right: int
) -> int | None:
if right < left:
return None
midpoint = left + (right - left) // 2
if sorted_collection[midpoint] == item:
return midpoint
elif sorted_collection[midpoint] > item:
... | searches |
def double_linear_search(array: list[int], search_item: int) -> int:
# define the start and end index of the given array
start_ind, end_ind = 0, len(array) - 1
while start_ind <= end_ind:
if array[start_ind] == search_item:
return start_ind
elif array[end_ind] == search_item:
... | searches |
def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int:
right = right or len(list_data) - 1
if left > right:
return -1
elif list_data[left] == key:
return left
elif list_data[right] == key:
return right
else:
return search(list_data, key, left + 1... | searches |
def sentinel_linear_search(sequence, target):
sequence.append(target)
index = 0
while sequence[index] != target:
index += 1
sequence.pop()
if index == len(sequence):
return None
return index | searches |
def _partition(data: list, pivot) -> tuple:
less, equal, greater = [], [], []
for element in data:
if element < pivot:
less.append(element)
elif element > pivot:
greater.append(element)
else:
equal.append(element)
return less, equal, greater | searches |
def lin_search(left: int, right: int, array: list[int], target: int) -> int:
for i in range(left, right):
if array[i] == target:
return i
return -1 | searches |
def ite_ternary_search(array: list[int], target: int) -> int:
left = 0
right = len(array)
while left <= right:
if right - left < precision:
return lin_search(left, right, array, target)
one_third = (left + right) // 3 + 1
two_third = 2 * (left + right) // 3 + 1
... | searches |
def rec_ternary_search(left: int, right: int, array: list[int], target: int) -> int:
if left < right:
if right - left < precision:
return lin_search(left, right, array, target)
one_third = (left + right) // 3 + 1
two_third = 2 * (left + right) // 3 + 1
if array[one_third... | searches |
def __init__(self, data):
self.data = data
self.right = None
self.left = None | searches |
def build_tree():
print("\n********Press N to stop entering at any point of time********\n")
check = input("Enter the value of the root node: ").strip().lower() or "n"
if check == "n":
return None
q: queue.Queue = queue.Queue()
tree_node = TreeNode(int(check))
q.put(tree_node)
while ... | searches |
def pre_order(node: TreeNode) -> None:
if not isinstance(node, TreeNode) or not node:
return
print(node.data, end=",")
pre_order(node.left)
pre_order(node.right) | searches |
def in_order(node: TreeNode) -> None:
if not isinstance(node, TreeNode) or not node:
return
in_order(node.left)
print(node.data, end=",")
in_order(node.right) | searches |
def post_order(node: TreeNode) -> None:
if not isinstance(node, TreeNode) or not node:
return
post_order(node.left)
post_order(node.right)
print(node.data, end=",") | searches |
def level_order(node: TreeNode) -> None:
if not isinstance(node, TreeNode) or not node:
return
q: queue.Queue = queue.Queue()
q.put(node)
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=",")
if node_dequeued.left:
q.put(node_dequeued... | searches |
def level_order_actual(node: TreeNode) -> None:
if not isinstance(node, TreeNode) or not node:
return
q: queue.Queue = queue.Queue()
q.put(node)
while not q.empty():
list_ = []
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=",")... | searches |
def pre_order_iter(node: TreeNode) -> None:
if not isinstance(node, TreeNode) or not node:
return
stack: list[TreeNode] = []
n = node
while n or stack:
while n: # start from root node, find its left child
print(n.data, end=",")
stack.append(n)
n = n.l... | searches |
def in_order_iter(node: TreeNode) -> None:
if not isinstance(node, TreeNode) or not node:
return
stack: list[TreeNode] = []
n = node
while n or stack:
while n:
stack.append(n)
n = n.left
n = stack.pop()
print(n.data, end=",")
n = n.right | searches |
def post_order_iter(node: TreeNode) -> None:
if not isinstance(node, TreeNode) or not node:
return
stack1, stack2 = [], []
n = node
stack1.append(n)
while stack1: # to find the reversed order of post order, store it in stack2
n = stack1.pop()
if n.left:
stack1.ap... | searches |
def prompt(s: str = "", width=50, char="*") -> str:
if not s:
return "\n" + width * char
left, extra = divmod(width - len(s) - 2, 2)
return f"{left * char} {s} {(left + extra) * char}" | searches |
def linear_search(sequence: list, target: int) -> int:
for index, item in enumerate(sequence):
if item == target:
return index
return -1 | searches |
def rec_linear_search(sequence: list, low: int, high: int, target: int) -> int:
if not (0 <= high < len(sequence) and 0 <= low < len(sequence)):
raise Exception("Invalid upper or lower bound!")
if high < low:
return -1
if sequence[low] == target:
return low
if sequence[high] == t... | searches |
def generate_neighbours(path):
dict_of_neighbours = {}
with open(path) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = []
_list.append([line.split()[1], line.split()[2]])
dict_of_neighbours[line.split()[0]] = _list
... | searches |
def generate_first_solution(path, dict_of_neighbours):
with open(path) as f:
start_node = f.read(1)
end_node = start_node
first_solution = []
visiting = start_node
distance_of_first_solution = 0
while visiting not in first_solution:
minim = 10000
for k in dict_of_neig... | searches |
def find_neighborhood(solution, dict_of_neighbours):
neighborhood_of_solution = []
for n in solution[1:-1]:
idx1 = solution.index(n)
for kn in solution[1:-1]:
idx2 = solution.index(kn)
if n == kn:
continue
_tmp = copy.deepcopy(solution)
... | searches |
def tabu_search(
first_solution, distance_of_first_solution, dict_of_neighbours, iters, size
):
count = 1
solution = first_solution
tabu_list = []
best_cost = distance_of_first_solution
best_solution_ever = solution
while count <= iters:
neighborhood = find_neighborhood(solution, di... | searches |
def main(args=None):
dict_of_neighbours = generate_neighbours(args.File)
first_solution, distance_of_first_solution = generate_first_solution(
args.File, dict_of_neighbours
)
best_sol, best_cost = tabu_search(
first_solution,
distance_of_first_solution,
dict_of_neighbou... | searches |
def interpolation_search(sorted_collection, item):
left = 0
right = len(sorted_collection) - 1
while left <= right:
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
... | searches |
def interpolation_search_by_recursion(sorted_collection, item, left, right):
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
else:
return None
point = left + ((item - s... | searches |
def __assert_sorted(collection):
if collection != sorted(collection):
raise ValueError("Collection must be ascending sorted")
return True | searches |
def fibonacci(k: int) -> int:
if not isinstance(k, int):
raise TypeError("k must be an integer.")
if k < 0:
raise ValueError("k integer must be greater or equal to zero.")
if k == 0:
return 0
elif k == 1:
return 1
else:
return fibonacci(k - 1) + fibonacci(k - ... | searches |
def fibonacci_search(arr: list, val: int) -> int:
len_list = len(arr)
# Find m such that F_m >= n where F_i is the i_th fibonacci number.
i = 0
while True:
if fibonacci(i) >= len_list:
fibb_k = i
break
i += 1
offset = 0
while fibb_k > 0:
index_k = ... | searches |
def jump_search(arr: list, x: int) -> int:
n = len(arr)
step = int(math.floor(math.sqrt(n)))
prev = 0
while arr[min(step, n) - 1] < x:
prev = step
step += int(math.floor(math.sqrt(n)))
if prev >= n:
return -1
while arr[prev] < x:
prev = prev + 1
... | searches |
def __init__(self, data: int) -> None:
self.data = data
self.rank: int
self.parent: Node | data_structures |
def make_set(x: Node) -> None:
# rank is the distance from x to its' parent
# root's rank is 0
x.rank = 0
x.parent = x | data_structures |
def union_set(x: Node, y: Node) -> None:
x, y = find_set(x), find_set(y)
if x == y:
return
elif x.rank > y.rank:
y.parent = x
else:
x.parent = y
if x.rank == y.rank:
y.rank += 1 | data_structures |
def find_set(x: Node) -> Node:
if x != x.parent:
x.parent = find_set(x.parent)
return x.parent | data_structures |
def find_python_set(node: Node) -> set:
sets = ({0, 1, 2}, {3, 4, 5})
for s in sets:
if node.data in s:
return s
raise ValueError(f"{node.data} is not in {sets}") | data_structures |
def test_disjoint_set() -> None:
vertex = [Node(i) for i in range(6)]
for v in vertex:
make_set(v)
union_set(vertex[0], vertex[1])
union_set(vertex[1], vertex[2])
union_set(vertex[3], vertex[4])
union_set(vertex[3], vertex[5])
for node0 in vertex:
for node1 in vertex:
... | data_structures |
def __init__(self, set_counts: list) -> None:
self.set_counts = set_counts
self.max_set = max(set_counts)
num_sets = len(set_counts)
self.ranks = [1] * num_sets
self.parents = list(range(num_sets)) | data_structures |
def merge(self, src: int, dst: int) -> bool:
src_parent = self.get_parent(src)
dst_parent = self.get_parent(dst)
if src_parent == dst_parent:
return False
if self.ranks[dst_parent] >= self.ranks[src_parent]:
self.set_counts[dst_parent] += self.set_counts[src_par... | data_structures |
def next_greatest_element_slow(arr: list[float]) -> list[float]:
result = []
arr_size = len(arr)
for i in range(arr_size):
next_element: float = -1
for j in range(i + 1, arr_size):
if arr[i] < arr[j]:
next_element = arr[j]
break
result.ap... | data_structures |
def next_greatest_element_fast(arr: list[float]) -> list[float]:
result = []
for i, outer in enumerate(arr):
next_item: float = -1
for inner in arr[i + 1 :]:
if outer < inner:
next_item = inner
break
result.append(next_item)
return result | data_structures |
def next_greatest_element(arr: list[float]) -> list[float]:
arr_size = len(arr)
stack: list[float] = []
result: list[float] = [-1] * arr_size
for index in reversed(range(arr_size)):
if stack:
while stack[-1] <= arr[index]:
stack.pop()
if not stack:
... | data_structures |
def is_operand(c):
return c.isdigit() | data_structures |
def evaluate(expression):
stack = []
# iterate over the string in reverse order
for c in expression.split()[::-1]:
# push operand to stack
if is_operand(c):
stack.append(int(c))
else:
# pop values from stack can calculate the result
# push the re... | data_structures |
def dijkstras_two_stack_algorithm(equation: str) -> int:
operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub}
operand_stack: Stack[int] = Stack()
operator_stack: Stack[str] = Stack()
for i in equation:
if i.isdigit():
# RULE 1
operand_stack.push(int(i))
... | data_structures |
def infix_2_postfix(infix):
stack = []
post_fix = []
priority = {
"^": 3,
"*": 2,
"/": 2,
"%": 2,
"+": 1,
"-": 1,
} # Priority of each operator
print_width = len(infix) if (len(infix) > 7) else 7
# Print table header for output
print(
... | data_structures |
def infix_2_prefix(infix):
infix = list(infix[::-1]) # reverse the infix equation
for i in range(len(infix)):
if infix[i] == "(":
infix[i] = ")" # change "(" to ")"
elif infix[i] == ")":
infix[i] = "(" # change ")" to "("
return (infix_2_postfix("".join(infix)))[... | data_structures |
def __init__(self, data: T):
self.data = data # Assign data
self.next: Node[T] | None = None # Initialize next as null
self.prev: Node[T] | None = None # Initialize prev as null | data_structures |
def __init__(self) -> None:
self.head: Node[T] | None = None | data_structures |
def push(self, data: T) -> None:
if self.head is None:
return None
else:
assert self.head is not None
temp = self.head.data
self.head = self.head.next
if self.head is not None:
self.head.prev = None
return temp | data_structures |
def balanced_parentheses(parentheses: str) -> bool:
stack: Stack[str] = Stack()
bracket_pairs = {"(": ")", "[": "]", "{": "}"}
for bracket in parentheses:
if bracket in bracket_pairs:
stack.push(bracket)
elif bracket in (")", "]", "}"):
if stack.is_empty() or bracket_... | data_structures |
def evaluate_postfix(postfix_notation: list) -> int:
if not postfix_notation:
return 0
operations = {"+", "-", "*", "/"}
stack: list[Any] = []
for token in postfix_notation:
if token in operations:
b, a = stack.pop(), stack.pop()
if token == "+":
... | data_structures |
def calculation_span(price, s):
n = len(price)
# Create a stack and push index of fist element to it
st = []
st.append(0)
# Span value of first element is always 1
s[0] = 1
# Calculate span values for rest of the elements
for i in range(1, n):
# Pop elements from stack while st... | data_structures |
def print_array(arr, n):
for i in range(0, n):
print(arr[i], end=" ") | data_structures |
def __init__(self, limit: int = 10):
self.stack: list[T] = []
self.limit = limit | data_structures |
def __bool__(self) -> bool:
return bool(self.stack) | data_structures |
def __str__(self) -> str:
return str(self.stack) | data_structures |
def push(self, data: T) -> None:
Pop an element off of the top of the stack.
>>> Stack().pop()
Traceback (most recent call last):
...
data_structures.stacks.stack.StackUnderflowError
Peek at the top-most element of the stack.
>>> Stack().pop()
Traceb... | data_structures |
def is_full(self) -> bool:
return self.size() == self.limit | data_structures |
def size(self) -> int:
return item in self.stack | data_structures |
def test_stack() -> None:
stack: Stack[int] = Stack(10)
assert bool(stack) is False
assert stack.is_empty() is True
assert stack.is_full() is False
assert str(stack) == "[]"
try:
_ = stack.pop()
raise AssertionError() # This should not happen
except StackUnderflowError:
... | data_structures |
def precedence(char: str) -> int:
return {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}.get(char, -1) | data_structures |
def infix_to_postfix(expression_str: str) -> str:
if not balanced_parentheses(expression_str):
raise ValueError("Mismatched parentheses")
stack: Stack[str] = Stack()
postfix = []
for char in expression_str:
if char.isalpha() or char.isdigit():
postfix.append(char)
eli... | data_structures |
def solve(post_fix):
stack = []
div = lambda x, y: int(x / y) # noqa: E731 integer division operation
opr = {
"^": op.pow,
"*": op.mul,
"/": div,
"+": op.add,
"-": op.sub,
} # operators & their respective operation
# print table header
print("Symbol".ce... | data_structures |
def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int):
if not root or root not in binary_tree_mirror_dictionary:
return
left_child, right_child = binary_tree_mirror_dictionary[root][:2]
binary_tree_mirror_dictionary[root] = [right_child, left_child]
binary_tree_mirror_dict(... | data_structures |
def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict:
if not binary_tree:
raise ValueError("binary tree cannot be empty")
if root not in binary_tree:
raise ValueError(f"root {root} is not present in the binary_tree")
binary_tree_mirror_dictionary = dict(binary_tree)
binary_tr... | data_structures |
def __init__(self, length: int) -> None:
self.minn: int = -1
self.maxx: int = -1
self.map_left: list[int] = [-1] * length
self.left: Node | None = None
self.right: Node | None = None | data_structures |
def __repr__(self) -> str:
return f"Node(min_value={self.minn} max_value={self.maxx})" | data_structures |
def build_tree(arr: list[int]) -> Node | None:
root = Node(len(arr))
root.minn, root.maxx = min(arr), max(arr)
# Leaf node case where the node contains only one unique value
if root.minn == root.maxx:
return root
pivot = (root.minn + root.maxx) // 2
left_arr: list[int] = []
right_ar... | data_structures |
def rank_till_index(node: Node | None, num: int, index: int) -> int:
if index < 0 or node is None:
return 0
# Leaf node cases
if node.minn == node.maxx:
return index + 1 if node.minn == num else 0
pivot = (node.minn + node.maxx) // 2
if num <= pivot:
# go the left subtree and... | data_structures |
def rank(node: Node | None, num: int, start: int, end: int) -> int:
if start > end:
return 0
rank_till_end = rank_till_index(node, num, end)
rank_before_start = rank_till_index(node, num, start - 1)
return rank_till_end - rank_before_start | data_structures |
def quantile(node: Node | None, index: int, start: int, end: int) -> int:
if index > (end - start) or start > end or node is None:
return -1
# Leaf node case
if node.minn == node.maxx:
return node.minn
# Number of elements in the left subtree in interval [start, end]
num_elements_in_... | data_structures |
def range_counting(
node: Node | None, start: int, end: int, start_num: int, end_num: int
) -> int:
if (
start > end
or node is None
or start_num > end_num
or node.minn > end_num
or node.maxx < start_num
):
return 0
if start_num <= node.minn and node.maxx ... | data_structures |
def __init__(self, value: int = 0) -> None:
self.value = value
self.left: Node | None = None
self.right: Node | None = None | data_structures |
def merge_two_binary_trees(tree1: Node | None, tree2: Node | None) -> Node | None:
if tree1 is None:
return tree2
if tree2 is None:
return tree1
tree1.value = tree1.value + tree2.value
tree1.left = merge_two_binary_trees(tree1.left, tree2.left)
tree1.right = merge_two_binary_trees(t... | data_structures |
def print_preorder(root: Node | None) -> None:
if root:
print(root.value)
print_preorder(root.left)
print_preorder(root.right) | data_structures |
End of preview. Expand in Data Studio
- Downloads last month
- 8