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:
queue.append(ind)
visited[ind] = True
parent[ind] = u
return visited[t] | 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 select path
path_flow = min(path_flow, graph[parent[s]][s])
s = parent[s]
max_flow += path_flow
v = sink
while v != source:
u = parent[v]
graph[u][v] -= path_flow
graph[v][u] += path_flow
v = parent[v]
for i in range(len(graph)):
for j in range(len(graph[0])):
if graph[i][j] == 0 and temp[i][j] > 0:
res.append((i, j))
return res | 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] > 0:
queue.append(ind)
visited[ind] = True
parent[ind] = u
return visited[t] | 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
path_flow = min(path_flow, graph[parent[s]][s])
s = parent[s]
max_flow += path_flow
v = sink
while v != source:
u = parent[v]
graph[u][v] -= path_flow
graph[v][u] += path_flow
v = parent[v]
return max_flow | 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[midpoint + 1 :], item) | 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,
) -> Any:
search_end = False
current_state = search_prob
current_temp = start_temperate
scores = []
iterations = 0
best_state = None
while not search_end:
current_score = current_state.score()
if best_state is None or current_score > best_state.score():
best_state = current_state
scores.append(current_score)
iterations += 1
next_state = None
neighbors = current_state.get_neighbors()
while (
next_state is None and neighbors
): # till we do not find a neighbor that we can move to
index = random.randint(0, len(neighbors) - 1) # picking a random neighbor
picked_neighbor = neighbors.pop(index)
change = picked_neighbor.score() - current_score
if (
picked_neighbor.x > max_x
or picked_neighbor.x < min_x
or picked_neighbor.y > max_y
or picked_neighbor.y < min_y
):
continue # neighbor outside our bounds
if not find_max:
change = change * -1 # in case we are finding minimum
if change > 0: # improves the solution
next_state = picked_neighbor
else:
probability = (math.e) ** (
change / current_temp
) # probability generation function
if random.random() < probability: # random number within probability
next_state = picked_neighbor
current_temp = current_temp - (current_temp * rate_of_decrease)
if current_temp < threshold_temp or next_state is None:
# temperature below threshold, or could not find a suitable neighbor
search_end = True
else:
current_state = next_state
if visualization:
from matplotlib import pyplot as plt
plt.plot(range(iterations), scores)
plt.xlabel("Iterations")
plt.ylabel("Function values")
plt.show()
return best_state | 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),
(self.x, self.y - step_size),
(self.x, self.y + step_size),
(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 store the current score at each iteration
iterations = 0
solution_found = False
visited = set()
while not solution_found and iterations < max_iter:
visited.add(current_state)
iterations += 1
current_score = current_state.score()
scores.append(current_score)
neighbors = current_state.get_neighbors()
max_change = -math.inf
min_change = math.inf
next_state = None # to hold the next best neighbor
for neighbor in neighbors:
if neighbor in visited:
continue # do not want to visit the same state again
if (
neighbor.x > max_x
or neighbor.x < min_x
or neighbor.y > max_y
or neighbor.y < min_y
):
continue # neighbor outside our bounds
change = neighbor.score() - current_score
if find_max: # finding max
# going to direction with greatest ascent
if change > max_change and change > 0:
max_change = change
next_state = neighbor
else: # finding min
# to direction with greatest descent
if change < min_change and change < 0:
min_change = change
next_state = neighbor
if next_state is not None:
# we found at least one neighbor which improved the current state
current_state = next_state
else:
# since we have no neighbor that improves the solution we stop the search
solution_found = True
if visualization:
from matplotlib import pyplot as plt
plt.plot(range(iterations), scores)
plt.xlabel("Iterations")
plt.ylabel("Function values")
plt.show()
return current_state | 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 lo | 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
elif item < current_item:
right = midpoint - 1
else:
left = midpoint + 1
return None | 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:
return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1)
else:
return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right) | 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:
return end_ind
else:
start_ind += 1
end_ind -= 1
# returns -1 if search_item is not found in array
return -1 | 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, right - 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
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
right = one_third - 1
elif array[two_third] < target:
left = two_third + 1
else:
left = one_third + 1
right = two_third - 1
else:
return -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] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
return rec_ternary_search(left, one_third - 1, array, target)
elif array[two_third] < target:
return rec_ternary_search(two_third + 1, right, array, target)
else:
return rec_ternary_search(one_third + 1, two_third - 1, array, target)
else:
return -1 | 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 not q.empty():
node_found = q.get()
msg = f"Enter the left node of {node_found.data}: "
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
left_node = TreeNode(int(check))
node_found.left = left_node
q.put(left_node)
msg = f"Enter the right node of {node_found.data}: "
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
right_node = TreeNode(int(check))
node_found.right = right_node
q.put(right_node)
return None | 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.left)
if node_dequeued.right:
q.put(node_dequeued.right) | 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=",")
if node_dequeued.left:
list_.append(node_dequeued.left)
if node_dequeued.right:
list_.append(node_dequeued.right)
print()
for node in list_:
q.put(node) | 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.left
# end of while means current node doesn't have left child
n = stack.pop()
# start to traverse its right child
n = n.right | 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.append(n.left)
if n.right:
stack1.append(n.right)
stack2.append(n)
while stack2: # pop up from stack2 will be the post order
print(stack2.pop().data, end=",") | 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] == target:
return high
return rec_linear_search(sequence, low + 1, high - 1, target) | 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
else:
dict_of_neighbours[line.split()[0]].append(
[line.split()[1], line.split()[2]]
)
if line.split()[1] not in dict_of_neighbours:
_list = []
_list.append([line.split()[0], line.split()[2]])
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append(
[line.split()[0], line.split()[2]]
)
return dict_of_neighbours | 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_neighbours[visiting]:
if int(k[1]) < int(minim) and k[0] not in first_solution:
minim = k[1]
best_node = k[0]
first_solution.append(visiting)
distance_of_first_solution = distance_of_first_solution + int(minim)
visiting = best_node
first_solution.append(end_node)
position = 0
for k in dict_of_neighbours[first_solution[-2]]:
if k[0] == start_node:
break
position += 1
distance_of_first_solution = (
distance_of_first_solution
+ int(dict_of_neighbours[first_solution[-2]][position][1])
- 10000
)
return first_solution, distance_of_first_solution | 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)
_tmp[idx1] = kn
_tmp[idx2] = n
distance = 0
for k in _tmp[:-1]:
next_node = _tmp[_tmp.index(k) + 1]
for i in dict_of_neighbours[k]:
if i[0] == next_node:
distance = distance + int(i[1])
_tmp.append(distance)
if _tmp not in neighborhood_of_solution:
neighborhood_of_solution.append(_tmp)
index_of_last_item_in_the_list = len(neighborhood_of_solution[0]) - 1
neighborhood_of_solution.sort(key=lambda x: x[index_of_last_item_in_the_list])
return neighborhood_of_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, dict_of_neighbours)
index_of_best_solution = 0
best_solution = neighborhood[index_of_best_solution]
best_cost_index = len(best_solution) - 1
found = False
while not found:
i = 0
while i < len(best_solution):
if best_solution[i] != solution[i]:
first_exchange_node = best_solution[i]
second_exchange_node = solution[i]
break
i = i + 1
if [first_exchange_node, second_exchange_node] not in tabu_list and [
second_exchange_node,
first_exchange_node,
] not in tabu_list:
tabu_list.append([first_exchange_node, second_exchange_node])
found = True
solution = best_solution[:-1]
cost = neighborhood[index_of_best_solution][best_cost_index]
if cost < best_cost:
best_cost = cost
best_solution_ever = solution
else:
index_of_best_solution = index_of_best_solution + 1
best_solution = neighborhood[index_of_best_solution]
if len(tabu_list) >= size:
tabu_list.pop(0)
count = count + 1
return best_solution_ever, best_cost | 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_neighbours,
args.Iterations,
args.Size,
)
print(f"Best solution: {best_sol}, with total distance: {best_cost}.") | 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
else:
return None
point = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(sorted_collection):
return None
current_item = sorted_collection[point]
if current_item == item:
return point
else:
if point < left:
right = left
left = point
elif point > right:
left = right
right = point
else:
if item < current_item:
right = point - 1
else:
left = point + 1
return None | 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 - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(sorted_collection):
return None
if sorted_collection[point] == item:
return point
elif point < left:
return interpolation_search_by_recursion(sorted_collection, item, point, left)
elif point > right:
return interpolation_search_by_recursion(sorted_collection, item, right, left)
else:
if sorted_collection[point] > item:
return interpolation_search_by_recursion(
sorted_collection, item, left, point - 1
)
else:
return interpolation_search_by_recursion(
sorted_collection, item, point + 1, right
) | 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 - 2) | 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 = min(
offset + fibonacci(fibb_k - 1), len_list - 1
) # Prevent out of range
item_k_1 = arr[index_k]
if item_k_1 == val:
return index_k
elif val < item_k_1:
fibb_k -= 1
elif val > item_k_1:
offset += fibonacci(fibb_k - 1)
fibb_k -= 2
else:
return -1 | 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
if prev == min(step, n):
return -1
if arr[prev] == x:
return prev
return -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:
if find_python_set(node0).isdisjoint(find_python_set(node1)):
assert find_set(node0) != find_set(node1)
else:
assert find_set(node0) == find_set(node1) | 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_parent]
self.set_counts[src_parent] = 0
self.parents[src_parent] = dst_parent
if self.ranks[dst_parent] == self.ranks[src_parent]:
self.ranks[dst_parent] += 1
joined_set_size = self.set_counts[dst_parent]
else:
self.set_counts[src_parent] += self.set_counts[dst_parent]
self.set_counts[dst_parent] = 0
self.parents[dst_parent] = src_parent
joined_set_size = self.set_counts[src_parent]
self.max_set = max(self.max_set, joined_set_size)
return True | 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.append(next_element)
return result | 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:
break
if stack:
result[index] = stack[-1]
stack.append(arr[index])
return result | 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 result onto the stack again
o1 = stack.pop()
o2 = stack.pop()
stack.append(calc[c](o1, o2))
return stack.pop() | 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))
elif i in operators:
# RULE 2
operator_stack.push(i)
elif i == ")":
# RULE 4
opr = operator_stack.peek()
operator_stack.pop()
num1 = operand_stack.peek()
operand_stack.pop()
num2 = operand_stack.peek()
operand_stack.pop()
total = operators[opr](num2, num1)
operand_stack.push(total)
# RULE 5
return operand_stack.peek() | 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(
"Symbol".center(8),
"Stack".center(print_width),
"Postfix".center(print_width),
sep=" | ",
)
print("-" * (print_width * 3 + 7))
for x in infix:
if x.isalpha() or x.isdigit():
post_fix.append(x) # if x is Alphabet / Digit, add it to Postfix
elif x == "(":
stack.append(x) # if x is "(" push to Stack
elif x == ")": # if x is ")" pop stack until "(" is encountered
while stack[-1] != "(":
post_fix.append(stack.pop()) # Pop stack & add the content to Postfix
stack.pop()
else:
if len(stack) == 0:
stack.append(x) # If stack is empty, push x to stack
else: # while priority of x is not > priority of element in the stack
while len(stack) > 0 and priority[x] <= priority[stack[-1]]:
post_fix.append(stack.pop()) # pop stack & add to Postfix
stack.append(x) # push x to stack
print(
x.center(8),
("".join(stack)).ljust(print_width),
("".join(post_fix)).ljust(print_width),
sep=" | ",
) # Output in tabular format
while len(stack) > 0: # while stack is not empty
post_fix.append(stack.pop()) # pop stack & add to Postfix
print(
" ".center(8),
("".join(stack)).ljust(print_width),
("".join(post_fix)).ljust(print_width),
sep=" | ",
) # Output in tabular format
return "".join(post_fix) # return Postfix as str | 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)))[
::-1
] # call infix_2_postfix on Infix, return reverse of Postfix | 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_pairs[stack.pop()] != bracket:
return False
return stack.is_empty() | 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 == "+":
stack.append(a + b)
elif token == "-":
stack.append(a - b)
elif token == "*":
stack.append(a * b)
else:
if a * b < 0 and a % b != 0:
stack.append(a // b + 1)
else:
stack.append(a // b)
else:
stack.append(int(token))
return stack.pop() | 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 stack is not
# empty and top of stack is smaller than price[i]
while len(st) > 0 and price[st[0]] <= price[i]:
st.pop()
# If stack becomes empty, then price[i] is greater
# than all elements on left of it, i.e. price[0],
# price[1], ..price[i-1]. Else the price[i] is
# greater than elements after top of stack
s[i] = i + 1 if len(st) <= 0 else (i - st[0])
# Push this element to stack
st.append(i) | 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()
Traceback (most recent call last):
...
data_structures.stacks.stack.StackUnderflowError
return not bool(self.stack) | 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:
assert True # This should happen
try:
_ = stack.peek()
raise AssertionError() # This should not happen
except StackUnderflowError:
assert True # This should happen
for i in range(10):
assert stack.size() == i
stack.push(i)
assert bool(stack)
assert not stack.is_empty()
assert stack.is_full()
assert str(stack) == str(list(range(10)))
assert stack.pop() == 9
assert stack.peek() == 8
stack.push(100)
assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100])
try:
stack.push(200)
raise AssertionError() # This should not happen
except StackOverflowError:
assert True # This should happen
assert not stack.is_empty()
assert stack.size() == 10
assert 5 in stack
assert 55 not in stack | 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)
elif char == "(":
stack.push(char)
elif char == ")":
while not stack.is_empty() and stack.peek() != "(":
postfix.append(stack.pop())
stack.pop()
else:
while not stack.is_empty() and precedence(char) <= precedence(stack.peek()):
postfix.append(stack.pop())
stack.push(char)
while not stack.is_empty():
postfix.append(stack.pop())
return " ".join(postfix) | 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".center(8), "Action".center(12), "Stack", sep=" | ")
print("-" * (30 + len(post_fix)))
for x in post_fix:
if x.isdigit(): # if x in digit
stack.append(x) # append x to stack
# output in tabular format
print(x.rjust(8), ("push(" + x + ")").ljust(12), ",".join(stack), sep=" | ")
else:
b = stack.pop() # pop stack
# output in tabular format
print("".rjust(8), ("pop(" + b + ")").ljust(12), ",".join(stack), sep=" | ")
a = stack.pop() # pop stack
# output in tabular format
print("".rjust(8), ("pop(" + a + ")").ljust(12), ",".join(stack), sep=" | ")
stack.append(
str(opr[x](int(a), int(b)))
) # evaluate the 2 values popped from stack & push result to stack
# output in tabular format
print(
x.rjust(8),
("push(" + a + x + b + ")").ljust(12),
",".join(stack),
sep=" | ",
)
return int(stack[0]) | 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(binary_tree_mirror_dictionary, left_child)
binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child) | 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_tree_mirror_dict(binary_tree_mirror_dictionary, root)
return binary_tree_mirror_dictionary | 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_arr: list[int] = []
for index, num in enumerate(arr):
if num <= pivot:
left_arr.append(num)
else:
right_arr.append(num)
root.map_left[index] = len(left_arr)
root.left = build_tree(left_arr)
root.right = build_tree(right_arr)
return root | 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 map index to the left subtree
return rank_till_index(node.left, num, node.map_left[index] - 1)
else:
# go to the right subtree and map index to the right subtree
return rank_till_index(node.right, num, index - node.map_left[index]) | 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_left_tree = node.map_left[end] - (
node.map_left[start - 1] if start else 0
)
if num_elements_in_left_tree > index:
return quantile(
node.left,
index,
(node.map_left[start - 1] if start else 0),
node.map_left[end] - 1,
)
else:
return quantile(
node.right,
index - num_elements_in_left_tree,
start - (node.map_left[start - 1] if start else 0),
end - node.map_left[end],
) | 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 <= end_num:
return end - start + 1
left = range_counting(
node.left,
(node.map_left[start - 1] if start else 0),
node.map_left[end] - 1,
start_num,
end_num,
)
right = range_counting(
node.right,
start - (node.map_left[start - 1] if start else 0),
end - node.map_left[end],
start_num,
end_num,
)
return left + right | 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(tree1.right, tree2.right)
return tree1 | 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 Dataset Viewer.
- Downloads last month
- 46