diff --git a/data_structures/arrays/sudoku_solver.py b/data_structures/arrays/sudoku_solver.py index d2fa43bbf298..05e2d9f7e964 100644 --- a/data_structures/arrays/sudoku_solver.py +++ b/data_structures/arrays/sudoku_solver.py @@ -41,7 +41,7 @@ def cross(items_a, items_b): peers = {s: {x for u in units[s] for x in u} - {s} for s in squares} -def test(): +def test() -> None: """A set of unit tests.""" assert len(squares) == 81 assert len(unitlist) == 27 @@ -121,7 +121,7 @@ def eliminate(values, s, d): return values -def display(values): +def display(values) -> None: """ Display these values as a 2-D grid. """ @@ -166,7 +166,7 @@ def search(values): return some(search(assign(values.copy(), s, d)) for d in values[s]) -def solve_all(grids, name="", showif=0.0): +def solve_all(grids, name="", showif=0.0) -> None: """ Attempt to solve a sequence of grids. Report results. When showif is a number of seconds, display puzzles that take longer. diff --git a/data_structures/binary_tree/binary_tree_mirror.py b/data_structures/binary_tree/binary_tree_mirror.py index b8548f4ec515..47cb7fc3917a 100644 --- a/data_structures/binary_tree/binary_tree_mirror.py +++ b/data_structures/binary_tree/binary_tree_mirror.py @@ -4,7 +4,7 @@ """ -def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int): +def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int) -> None: if not root or root not in binary_tree_mirror_dictionary: return left_child, right_child = binary_tree_mirror_dictionary[root][:2] diff --git a/data_structures/binary_tree/segment_tree.py b/data_structures/binary_tree/segment_tree.py index 084fcf84955d..07b8eb157c8c 100644 --- a/data_structures/binary_tree/segment_tree.py +++ b/data_structures/binary_tree/segment_tree.py @@ -35,7 +35,7 @@ def right(self, idx): """ return idx * 2 + 1 - def build(self, idx, left, right): + def build(self, idx, left, right) -> None: if left == right: self.st[idx] = self.A[left] else: @@ -56,7 +56,7 @@ def update(self, a, b, val): """ return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val) - def update_recursive(self, idx, left, right, a, b, val): + def update_recursive(self, idx, left, right, a, b, val) -> bool: """ update(1, 1, N, a, b, v) for update val v to [a,b] """ @@ -96,7 +96,7 @@ def query_recursive(self, idx, left, right, a, b): q2 = self.query_recursive(self.right(idx), mid + 1, right, a, b) return max(q1, q2) - def show_data(self): + def show_data(self) -> None: show_list = [] for i in range(1, self.N + 1): show_list += [self.query(i, i)] diff --git a/data_structures/binary_tree/segment_tree_other.py b/data_structures/binary_tree/segment_tree_other.py index 95f21ddd4777..7814ff26daee 100644 --- a/data_structures/binary_tree/segment_tree_other.py +++ b/data_structures/binary_tree/segment_tree_other.py @@ -133,7 +133,7 @@ def __init__(self, collection: Sequence, function): if self.collection: self.root = self._build_tree(0, len(collection) - 1) - def update(self, i, val): + def update(self, i, val) -> None: """ Update an element in log(N) time :param i: position to be update diff --git a/data_structures/hashing/hash_table.py b/data_structures/hashing/hash_table.py index 40fcad9a3dab..a5f37af4cf64 100644 --- a/data_structures/hashing/hash_table.py +++ b/data_structures/hashing/hash_table.py @@ -85,7 +85,7 @@ def _step_by_step(self, step_ord): print(list(range(len(self.values)))) print(self.values) - def bulk_insert(self, values): + def bulk_insert(self, values) -> None: """ bulk_insert is used for entering more than one element at a time in the HashTable. @@ -236,7 +236,7 @@ def _collision_resolution(self, key, data=None): return new_key - def rehashing(self): + def rehashing(self) -> None: 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() @@ -244,7 +244,7 @@ def rehashing(self): for value in survivor_values: self.insert_data(value) - def insert_data(self, data): + def insert_data(self, data) -> None: """ insert_data is used for inserting a single element at a time in the HashTable. diff --git a/data_structures/hashing/tests/test_hash_map.py b/data_structures/hashing/tests/test_hash_map.py index 4292c0178b7b..0ec55595965e 100644 --- a/data_structures/hashing/tests/test_hash_map.py +++ b/data_structures/hashing/tests/test_hash_map.py @@ -74,7 +74,7 @@ def _run_operation(obj, fun, *args): pytest.param(_add_with_resize_down, id="add with resize down"), ], ) -def test_hash_map_is_the_same_as_dict(operations): +def test_hash_map_is_the_same_as_dict(operations) -> None: my = HashMap(initial_block_size=4) py = {} for _, (fun, *args) in enumerate(operations): @@ -87,7 +87,7 @@ def test_hash_map_is_the_same_as_dict(operations): assert set(my.items()) == set(py.items()) -def test_no_new_methods_was_added_to_api(): +def test_no_new_methods_was_added_to_api() -> None: def is_public(name: str) -> bool: return not name.startswith("_") diff --git a/data_structures/heap/binomial_heap.py b/data_structures/heap/binomial_heap.py index c97ec1c32149..eedc5b159bc1 100644 --- a/data_structures/heap/binomial_heap.py +++ b/data_structures/heap/binomial_heap.py @@ -203,7 +203,7 @@ def merge_heaps(self, other): # Return the merged heap return self - def insert(self, val): + def insert(self, val) -> None: """ insert a value in the heap """ diff --git a/data_structures/heap/min_heap.py b/data_structures/heap/min_heap.py index 577b98d788a1..3916cf3c9334 100644 --- a/data_structures/heap/min_heap.py +++ b/data_structures/heap/min_heap.py @@ -64,7 +64,7 @@ def build_heap(self, array): return array # this is min-heapify method - def sift_down(self, idx, array): + def sift_down(self, idx, array) -> None: while True: left = self.get_left_child_idx(idx) right = self.get_right_child_idx(idx) @@ -88,7 +88,7 @@ def sift_down(self, idx, array): else: break - def sift_up(self, idx): + def sift_up(self, idx) -> None: 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] @@ -114,7 +114,7 @@ def remove(self): self.sift_down(0, self.heap) return x - def insert(self, node): + def insert(self, node) -> None: self.heap.append(node) self.idx_of_element[node] = len(self.heap) - 1 self.heap_dict[node.name] = node.val @@ -123,7 +123,7 @@ def insert(self, node): def is_empty(self): return len(self.heap) == 0 - def decrease_key(self, node, new_value): + def decrease_key(self, node, new_value) -> None: assert self.heap[self.idx_of_element[node]].val > new_value, ( "newValue must be less that current value" ) diff --git a/data_structures/kd_tree/tests/test_kdtree.py b/data_structures/kd_tree/tests/test_kdtree.py index d6a4a66dd24d..4722aeb477c6 100644 --- a/data_structures/kd_tree/tests/test_kdtree.py +++ b/data_structures/kd_tree/tests/test_kdtree.py @@ -23,7 +23,9 @@ (10, 10.0, 3, -2, KDNode), # Depth = -2, 3D points ], ) -def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_result): +def test_build_kdtree( + num_points, cube_size, num_dimensions, depth, expected_result +) -> None: """ Test that KD-Tree is built correctly. @@ -58,7 +60,7 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res ) -def test_nearest_neighbour_search(): +def test_nearest_neighbour_search() -> None: """ Test the nearest neighbor search function. """ @@ -85,7 +87,7 @@ def test_nearest_neighbour_search(): assert nodes_visited >= 0 -def test_edge_cases(): +def test_edge_cases() -> None: """ Test edge cases such as an empty KD-Tree. """ diff --git a/data_structures/linked_list/doubly_linked_list.py b/data_structures/linked_list/doubly_linked_list.py index 1eee15edf714..9561bfcf879d 100644 --- a/data_structures/linked_list/doubly_linked_list.py +++ b/data_structures/linked_list/doubly_linked_list.py @@ -57,13 +57,13 @@ def __len__(self): """ return sum(1 for _ in self) - def insert_at_head(self, data): + def insert_at_head(self, data) -> None: self.insert_at_nth(0, data) - def insert_at_tail(self, data): + def insert_at_tail(self, data) -> None: self.insert_at_nth(len(self), data) - def insert_at_nth(self, index: int, data): + def insert_at_nth(self, index: int, data) -> None: """ >>> linked_list = DoublyLinkedList() >>> linked_list.insert_at_nth(-1, 666) diff --git a/data_structures/linked_list/doubly_linked_list_two.py b/data_structures/linked_list/doubly_linked_list_two.py index a7f639a6e289..32f024e27da9 100644 --- a/data_structures/linked_list/doubly_linked_list_two.py +++ b/data_structures/linked_list/doubly_linked_list_two.py @@ -138,7 +138,7 @@ def get_node(self, item: DataType) -> Node: node = node.next raise Exception("Node not found") - def delete_value(self, value): + def delete_value(self, value) -> None: if (node := self.get_node(value)) is not None: if node == self.head: self.head = self.head.next diff --git a/data_structures/linked_list/singly_linked_list.py b/data_structures/linked_list/singly_linked_list.py index 3ec91242d62c..6f1dfebf527e 100644 --- a/data_structures/linked_list/singly_linked_list.py +++ b/data_structures/linked_list/singly_linked_list.py @@ -498,7 +498,7 @@ def test_singly_linked_list_2() -> None: ) -def main(): +def main() -> None: from doctest import testmod testmod() diff --git a/data_structures/linked_list/skip_list.py b/data_structures/linked_list/skip_list.py index f21ca70bbc82..dca9966e8a54 100644 --- a/data_structures/linked_list/skip_list.py +++ b/data_structures/linked_list/skip_list.py @@ -160,7 +160,7 @@ def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: else: return None, update_vector - def delete(self, key: KT): + def delete(self, key: KT) -> None: """ :param key: Key to remove from list. @@ -186,7 +186,7 @@ def delete(self, key: KT): else: update_node.forward = update_node.forward[:i] - def insert(self, key: KT, value: VT): + def insert(self, key: KT, value: VT) -> None: """ :param key: Key to insert. :param value: Value associated with given key. @@ -246,7 +246,7 @@ def find(self, key: VT) -> VT | None: return None -def test_insert(): +def test_insert() -> None: skip_list = SkipList() skip_list.insert("Key1", 3) skip_list.insert("Key2", 12) @@ -266,7 +266,7 @@ def test_insert(): assert all_values["Key4"] == -19 -def test_insert_overrides_existing_value(): +def test_insert_overrides_existing_value() -> None: skip_list = SkipList() skip_list.insert("Key1", 10) skip_list.insert("Key1", 12) @@ -294,12 +294,12 @@ def test_insert_overrides_existing_value(): assert all_values["Key10"] == 10 -def test_searching_empty_list_returns_none(): +def test_searching_empty_list_returns_none() -> None: skip_list = SkipList() assert skip_list.find("Some key") is None -def test_search(): +def test_search() -> None: skip_list = SkipList() skip_list.insert("Key2", 20) @@ -315,14 +315,14 @@ def test_search(): assert skip_list.find("V") == 13 -def test_deleting_item_from_empty_list_do_nothing(): +def test_deleting_item_from_empty_list_do_nothing() -> None: skip_list = SkipList() skip_list.delete("Some key") assert len(skip_list.head.forward) == 0 -def test_deleted_items_are_not_founded_by_find_method(): +def test_deleted_items_are_not_founded_by_find_method() -> None: skip_list = SkipList() skip_list.insert("Key1", 12) @@ -337,7 +337,7 @@ def test_deleted_items_are_not_founded_by_find_method(): assert skip_list.find("Key2") is None -def test_delete_removes_only_given_key(): +def test_delete_removes_only_given_key() -> None: skip_list = SkipList() skip_list.insert("Key1", 12) @@ -370,7 +370,7 @@ def test_delete_removes_only_given_key(): assert skip_list.find("Key2") is None -def test_delete_doesnt_leave_dead_nodes(): +def test_delete_doesnt_leave_dead_nodes() -> None: skip_list = SkipList() skip_list.insert("Key1", 12) @@ -388,7 +388,7 @@ def traverse_keys(node): assert len(set(traverse_keys(skip_list.head))) == 4 -def test_iter_always_yields_sorted_values(): +def test_iter_always_yields_sorted_values() -> None: def is_sorted(lst): return all(next_item >= item for item, next_item in pairwise(lst)) @@ -405,7 +405,7 @@ def is_sorted(lst): assert is_sorted(list(skip_list)) -def pytests(): +def pytests() -> None: for _ in range(100): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs @@ -423,7 +423,7 @@ def pytests(): test_iter_always_yields_sorted_values() -def main(): +def main() -> None: """ >>> pytests() """ diff --git a/data_structures/queues/priority_queue_using_list.py b/data_structures/queues/priority_queue_using_list.py index 15e56c557069..b4667e451919 100644 --- a/data_structures/queues/priority_queue_using_list.py +++ b/data_structures/queues/priority_queue_using_list.py @@ -177,7 +177,7 @@ def __str__(self) -> str: return str(self.queue) -def fixed_priority_queue(): +def fixed_priority_queue() -> None: fpq = FixedPriorityQueue() fpq.enqueue(0, 10) fpq.enqueue(1, 70) @@ -202,7 +202,7 @@ def fixed_priority_queue(): print(fpq.dequeue()) -def element_priority_queue(): +def element_priority_queue() -> None: epq = ElementPriorityQueue() epq.enqueue(10) epq.enqueue(70) diff --git a/data_structures/stacks/stock_span_problem.py b/data_structures/stacks/stock_span_problem.py index 74c2636784e2..7a364f0debb6 100644 --- a/data_structures/stacks/stock_span_problem.py +++ b/data_structures/stacks/stock_span_problem.py @@ -58,7 +58,7 @@ def calculate_span(price: list[int]) -> list[int]: # A utility function to print elements of array -def print_array(arr, n): +def print_array(arr, n) -> None: for i in range(n): print(arr[i], end=" ") diff --git a/digital_image_processing/edge_detection/canny.py b/digital_image_processing/edge_detection/canny.py index 944161c31cfc..450e061f712d 100644 --- a/digital_image_processing/edge_detection/canny.py +++ b/digital_image_processing/edge_detection/canny.py @@ -72,7 +72,7 @@ def suppress_non_maximum(image_shape, gradient_direction, sobel_grad): def detect_high_low_threshold( image_shape, destination, threshold_low, threshold_high, weak, strong -): +) -> None: """ High-Low threshold detection. If an edge pixel's gradient value is higher than the high threshold value, it is marked as a strong edge pixel. If an @@ -91,7 +91,7 @@ def detect_high_low_threshold( destination[row, col] = weak -def track_edge(image_shape, destination, weak, strong): +def track_edge(image_shape, destination, weak, strong) -> None: """ Edge tracking. Usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while noise responses are unconnected. As long as there is diff --git a/digital_image_processing/histogram_equalization/histogram_stretch.py b/digital_image_processing/histogram_equalization/histogram_stretch.py index 1270c964dee6..94a9bd6be9f7 100644 --- a/digital_image_processing/histogram_equalization/histogram_stretch.py +++ b/digital_image_processing/histogram_equalization/histogram_stretch.py @@ -24,7 +24,7 @@ def __init__(self): self.number_of_rows = 0 self.number_of_cols = 0 - def stretch(self, input_image): + def stretch(self, input_image) -> None: self.img = cv2.imread(input_image, 0) self.original_image = copy.deepcopy(self.img) x, _, _ = plt.hist(self.img.ravel(), 256, [0, 256], label="x") @@ -46,10 +46,10 @@ def stretch(self, input_image): self.img[j][i] = self.last_list[num] cv2.imwrite("output_data/output.jpg", self.img) - def plot_histogram(self): + def plot_histogram(self) -> None: plt.hist(self.img.ravel(), 256, [0, 256]) - def show_image(self): + def show_image(self) -> None: cv2.imshow("Output-Image", self.img) cv2.imshow("Input-Image", self.original_image) cv2.waitKey(5000) diff --git a/digital_image_processing/index_calculation.py b/digital_image_processing/index_calculation.py index 988f8e72b9a8..b0b15312f735 100644 --- a/digital_image_processing/index_calculation.py +++ b/digital_image_processing/index_calculation.py @@ -107,7 +107,9 @@ class IndexCalculation: def __init__(self, red=None, green=None, blue=None, red_edge=None, nir=None): self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) - def set_matricies(self, red=None, green=None, blue=None, red_edge=None, nir=None): + def set_matricies( + self, red=None, green=None, blue=None, red_edge=None, nir=None + ) -> bool: if red is not None: self.red = red if green is not None: diff --git a/digital_image_processing/resize/resize.py b/digital_image_processing/resize/resize.py index 7bde118da69b..dfff8407c3e8 100644 --- a/digital_image_processing/resize/resize.py +++ b/digital_image_processing/resize/resize.py @@ -27,7 +27,7 @@ def __init__(self, img, dst_width: int, dst_height: int): np.ones((self.dst_h, self.dst_w, 3), np.uint8) * 255 ) - def process(self): + def process(self) -> None: for i in range(self.dst_h): for j in range(self.dst_w): self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)] diff --git a/digital_image_processing/test_digital_image_processing.py b/digital_image_processing/test_digital_image_processing.py index d1200f4d65ca..4bc0fb94b900 100644 --- a/digital_image_processing/test_digital_image_processing.py +++ b/digital_image_processing/test_digital_image_processing.py @@ -24,14 +24,14 @@ # Test: convert_to_negative() -def test_convert_to_negative(): +def test_convert_to_negative() -> None: negative_img = cn.convert_to_negative(img) # assert negative_img array for at least one True assert negative_img.any() # Test: change_contrast() -def test_change_contrast(): +def test_change_contrast() -> None: with Image.open("digital_image_processing/image_data/lena_small.jpg") as img: # Work around assertion for response assert str(cc.change_contrast(img, 110)).startswith( @@ -40,14 +40,14 @@ def test_change_contrast(): # canny.gen_gaussian_kernel() -def test_gen_gaussian_kernel(): +def test_gen_gaussian_kernel() -> None: resp = canny.gen_gaussian_kernel(9, sigma=1.4) # Assert ambiguous array assert resp.all() # canny.py -def test_canny(): +def test_canny() -> None: canny_img = imread("digital_image_processing/image_data/lena_small.jpg", 0) # assert ambiguous array for all == True assert canny_img.all() @@ -57,33 +57,35 @@ def test_canny(): # filters/gaussian_filter.py -def test_gen_gaussian_kernel_filter(): +def test_gen_gaussian_kernel_filter() -> None: assert gg.gaussian_filter(gray, 5, sigma=0.9).all() -def test_convolve_filter(): +def test_convolve_filter() -> None: # laplace diagonals laplace = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]) res = conv.img_convolve(gray, laplace).astype(uint8) assert res.any() -def test_median_filter(): +def test_median_filter() -> None: assert med.median_filter(gray, 3).any() -def test_sobel_filter(): +def test_sobel_filter() -> None: grad, theta = sob.sobel_filter(gray) assert grad.any() assert theta.any() -def test_sepia(): +def test_sepia() -> None: sepia = sp.make_sepia(img, 20) assert sepia.all() -def test_burkes(file_path: str = "digital_image_processing/image_data/lena_small.jpg"): +def test_burkes( + file_path: str = "digital_image_processing/image_data/lena_small.jpg", +) -> None: burkes = bs.Burkes(imread(file_path, 1), 120) burkes.process() assert burkes.output_img.any() @@ -91,13 +93,13 @@ def test_burkes(file_path: str = "digital_image_processing/image_data/lena_small def test_nearest_neighbour( file_path: str = "digital_image_processing/image_data/lena_small.jpg", -): +) -> None: nn = rs.NearestNeighbour(imread(file_path, 1), 400, 200) nn.process() assert nn.output.any() -def test_local_binary_pattern(): +def test_local_binary_pattern() -> None: # pull request 10161 before: # "digital_image_processing/image_data/lena.jpg" # after: "digital_image_processing/image_data/lena_small.jpg" diff --git a/divide_and_conquer/convex_hull.py b/divide_and_conquer/convex_hull.py index b1ab33cc9415..4fd00d551a87 100644 --- a/divide_and_conquer/convex_hull.py +++ b/divide_and_conquer/convex_hull.py @@ -477,7 +477,7 @@ def convex_hull_melkman(points: list[Point]) -> list[Point]: return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull) -def main(): +def main() -> None: points = [ (0, 3), (2, 2), diff --git a/divide_and_conquer/inversions.py b/divide_and_conquer/inversions.py index 35f78fe5cf1e..d38dcf589e46 100644 --- a/divide_and_conquer/inversions.py +++ b/divide_and_conquer/inversions.py @@ -118,7 +118,7 @@ def _count_cross_inversions(p, q): return r, num_inversion -def main(): +def main() -> None: arr_1 = [10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: diff --git a/dynamic_programming/floyd_warshall.py b/dynamic_programming/floyd_warshall.py index b92c6667fb5c..ed88da1b0971 100644 --- a/dynamic_programming/floyd_warshall.py +++ b/dynamic_programming/floyd_warshall.py @@ -11,7 +11,7 @@ def __init__(self, n=0): # a graph with Node 0,1,...,N-1 [math.inf for j in range(n)] for i in range(n) ] # dp[i][j] stores minimum distance from i to j - def add_edge(self, u, v, w): + def add_edge(self, u, v, w) -> None: """ Adds a directed edge from node u to node v with weight w. @@ -23,7 +23,7 @@ def add_edge(self, u, v, w): """ self.dp[u][v] = w - def floyd_warshall(self): + def floyd_warshall(self) -> None: """ Computes the shortest paths between all pairs of nodes using the Floyd-Warshall algorithm. diff --git a/dynamic_programming/matrix_chain_order.py b/dynamic_programming/matrix_chain_order.py index 6df43e84be28..949d535dc985 100644 --- a/dynamic_programming/matrix_chain_order.py +++ b/dynamic_programming/matrix_chain_order.py @@ -34,7 +34,7 @@ def matrix_chain_order(array: list[int]) -> tuple[list[list[int]], list[list[int return matrix, sol -def print_optimal_solution(optimal_solution: list[list[int]], i: int, j: int): +def print_optimal_solution(optimal_solution: list[list[int]], i: int, j: int) -> None: """ Print order of matrix with Ai as Matrix. """ @@ -48,7 +48,7 @@ def print_optimal_solution(optimal_solution: list[list[int]], i: int, j: int): print(")", end=" ") -def main(): +def main() -> None: """ Size of matrix created from array [30, 35, 15, 5, 10, 20, 25] will be: 30*35 35*15 15*5 5*10 10*20 20*25 diff --git a/dynamic_programming/optimal_binary_search_tree.py b/dynamic_programming/optimal_binary_search_tree.py index b4f1181ac11c..0df36afea01b 100644 --- a/dynamic_programming/optimal_binary_search_tree.py +++ b/dynamic_programming/optimal_binary_search_tree.py @@ -35,7 +35,7 @@ def __str__(self): return f"Node(key={self.key}, freq={self.freq})" -def print_binary_search_tree(root, key, i, j, parent, is_left): +def print_binary_search_tree(root, key, i, j, parent, is_left) -> None: """ Recursive function to print a BST from a root table. @@ -65,7 +65,7 @@ def print_binary_search_tree(root, key, i, j, parent, is_left): print_binary_search_tree(root, key, node + 1, j, key[node], False) -def find_optimal_binary_search_tree(nodes): +def find_optimal_binary_search_tree(nodes) -> None: """ This function calculates and prints the optimal binary search tree. The dynamic programming algorithm below runs in O(n^2) time. @@ -134,7 +134,7 @@ def find_optimal_binary_search_tree(nodes): print_binary_search_tree(root, keys, 0, n - 1, -1, False) -def main(): +def main() -> None: # A sample binary search tree nodes = [Node(i, randint(1, 50)) for i in range(10, 0, -1)] find_optimal_binary_search_tree(nodes) diff --git a/dynamic_programming/rod_cutting.py b/dynamic_programming/rod_cutting.py index d12c759dc928..6bb58ffbde44 100644 --- a/dynamic_programming/rod_cutting.py +++ b/dynamic_programming/rod_cutting.py @@ -197,7 +197,7 @@ def _enforce_args(n: int, prices: list): raise ValueError(msg) -def main(): +def main() -> None: prices = [6, 10, 12, 15, 20, 23] n = len(prices) diff --git a/file_transfer/receive_file.py b/file_transfer/receive_file.py index f50ad9fe1107..b626d2e39b06 100644 --- a/file_transfer/receive_file.py +++ b/file_transfer/receive_file.py @@ -1,7 +1,7 @@ import socket -def main(): +def main() -> None: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 12312 diff --git a/file_transfer/tests/test_send_file.py b/file_transfer/tests/test_send_file.py index 2a6008448362..416c2779e3ef 100644 --- a/file_transfer/tests/test_send_file.py +++ b/file_transfer/tests/test_send_file.py @@ -5,7 +5,7 @@ @patch("socket.socket") @patch("builtins.open") -def test_send_file_running_as_expected(file, sock): +def test_send_file_running_as_expected(file, sock) -> None: # ===== initialization ===== conn = Mock() sock.return_value.accept.return_value = conn, Mock() diff --git a/fractals/vicsek.py b/fractals/vicsek.py index 290fe95b79b4..a4b5fe777fc7 100644 --- a/fractals/vicsek.py +++ b/fractals/vicsek.py @@ -15,7 +15,7 @@ import turtle -def draw_cross(x: float, y: float, length: float): +def draw_cross(x: float, y: float, length: float) -> None: """ Draw a cross at the specified position and with the specified length. """ @@ -34,7 +34,7 @@ def draw_cross(x: float, y: float, length: float): turtle.end_fill() -def draw_fractal_recursive(x: float, y: float, length: float, depth: float): +def draw_fractal_recursive(x: float, y: float, length: float, depth: float) -> None: """ Recursively draw the Vicsek fractal at the specified position, with the specified length and depth. @@ -50,11 +50,13 @@ def draw_fractal_recursive(x: float, y: float, length: float, depth: float): draw_fractal_recursive(x, y - length / 3, length / 3, depth - 1) -def set_color(rgb: str): +def set_color(rgb: str) -> None: turtle.color(rgb) -def draw_vicsek_fractal(x: float, y: float, length: float, depth: float, color="blue"): +def draw_vicsek_fractal( + x: float, y: float, length: float, depth: float, color="blue" +) -> None: """ Draw the Vicsek fractal at the specified position, with the specified length and depth. @@ -66,7 +68,7 @@ def draw_vicsek_fractal(x: float, y: float, length: float, depth: float, color=" turtle.Screen().update() -def main(): +def main() -> None: draw_vicsek_fractal(0, 0, 800, 4) turtle.done() diff --git a/fuzzy_logic/fuzzy_operations.py b/fuzzy_logic/fuzzy_operations.py index 37833b119b16..231f18932975 100644 --- a/fuzzy_logic/fuzzy_operations.py +++ b/fuzzy_logic/fuzzy_operations.py @@ -156,7 +156,7 @@ def union(self, other) -> FuzzySet: max(self.right_boundary, other.right_boundary), ) - def plot(self): + def plot(self) -> None: """ Plot the membership function of the fuzzy set. """ diff --git a/graphics/bezier_curve.py b/graphics/bezier_curve.py index 03d1113cbb3f..774a43e4fa83 100644 --- a/graphics/bezier_curve.py +++ b/graphics/bezier_curve.py @@ -92,7 +92,7 @@ def derivative(self, t: float) -> tuple[float, float]: dy += coeff * delta_y * n return (dx, dy) - def plot_curve(self, step_size: float = 0.01): + def plot_curve(self, step_size: float = 0.01) -> None: """ Plots the Bezier curve using matplotlib plotting capabilities. step_size: defines the step(s) at which to evaluate the Bezier curve. diff --git a/graphs/articulation_points.py b/graphs/articulation_points.py index 0bf16e55bc04..1de20e13752b 100644 --- a/graphs/articulation_points.py +++ b/graphs/articulation_points.py @@ -1,5 +1,5 @@ # Finding Articulation Points in Undirected Graph -def compute_ap(graph): +def compute_ap(graph) -> None: n = len(graph) out_edge_count = 0 low = [0] * n diff --git a/graphs/basic_graphs.py b/graphs/basic_graphs.py index 286e9b195796..ff41d23bc4c6 100644 --- a/graphs/basic_graphs.py +++ b/graphs/basic_graphs.py @@ -76,7 +76,7 @@ def initialize_weighted_undirected_graph( """ -def dfs(g, s): +def dfs(g, s) -> None: """ >>> dfs({1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}, 1) 1 @@ -111,7 +111,7 @@ def dfs(g, s): """ -def bfs(g, s): +def bfs(g, s) -> None: """ >>> bfs({1: [2, 3], 2: [4, 5], 3: [6, 7], 4: [], 5: [8], 6: [], 7: [], 8: []}, 1) 1 @@ -146,7 +146,7 @@ def bfs(g, s): """ -def dijk(g, s): +def dijk(g, s) -> None: """ dijk({1: [(2, 7), (3, 9), (6, 14)], 2: [(1, 7), (3, 10), (4, 15)], @@ -186,7 +186,7 @@ def dijk(g, s): """ -def topo(g, ind=None, q=None): +def topo(g, ind=None, q=None) -> None: if q is None: q = [1] if ind is None: @@ -256,7 +256,7 @@ def adjm(): """ -def floy(a_and_n): +def floy(a_and_n) -> None: (a, n) = a_and_n dist = list(a) path = [[0] * n for i in range(n)] @@ -347,7 +347,7 @@ def edglist(): """ -def krusk(e_and_n): +def krusk(e_and_n) -> None: """ Sort edges on the basis of distance """ diff --git a/graphs/bellman_ford.py b/graphs/bellman_ford.py index 9ac8bae85d4f..da8526f08827 100644 --- a/graphs/bellman_ford.py +++ b/graphs/bellman_ford.py @@ -1,7 +1,7 @@ from __future__ import annotations -def print_distance(distance: list[float], src): +def print_distance(distance: list[float], src) -> None: print(f"Vertex\tShortest Distance from vertex {src}") for i, d in enumerate(distance): print(f"{i}\t\t{d}") @@ -9,7 +9,7 @@ def print_distance(distance: list[float], src): def check_negative_cycle( graph: list[dict[str, int]], distance: list[float], edge_count: int -): +) -> bool: for j in range(edge_count): u, v, w = (graph[j][k] for k in ["src", "dst", "weight"]) if distance[u] != float("inf") and distance[u] + w < distance[v]: diff --git a/graphs/breadth_first_search_zero_one_shortest_path.py b/graphs/breadth_first_search_zero_one_shortest_path.py index d3a255bac1ef..7f9679afb598 100644 --- a/graphs/breadth_first_search_zero_one_shortest_path.py +++ b/graphs/breadth_first_search_zero_one_shortest_path.py @@ -34,7 +34,7 @@ def __getitem__(self, vertex: int) -> Iterator[Edge]: def size(self): return self._size - def add_edge(self, from_vertex: int, to_vertex: int, weight: int): + def add_edge(self, from_vertex: int, to_vertex: int, weight: int) -> None: """ >>> g = AdjacencyList(2) >>> g.add_edge(0, 1, 0) diff --git a/graphs/dijkstra_2.py b/graphs/dijkstra_2.py index f548463ff7bd..771a017591aa 100644 --- a/graphs/dijkstra_2.py +++ b/graphs/dijkstra_2.py @@ -1,4 +1,4 @@ -def print_dist(dist, v): +def print_dist(dist, v) -> None: print("\nVertex Distance") for i in range(v): if dist[i] != float("inf"): @@ -18,7 +18,7 @@ def min_dist(mdist, vset, v): return min_ind -def dijkstra(graph, v, src): +def dijkstra(graph, v, src) -> None: mdist = [float("inf") for _ in range(v)] vset = [False for _ in range(v)] mdist[src] = 0.0 diff --git a/graphs/dijkstra_algorithm.py b/graphs/dijkstra_algorithm.py index 60646862fca8..ae8465e3f601 100644 --- a/graphs/dijkstra_algorithm.py +++ b/graphs/dijkstra_algorithm.py @@ -41,7 +41,7 @@ def is_empty(self): """ return self.cur_size == 0 - def min_heapify(self, idx): + def min_heapify(self, idx) -> None: """ Sorts the queue array so that the minimum element is root. @@ -84,7 +84,7 @@ def min_heapify(self, idx): self.swap(idx, smallest) self.min_heapify(smallest) - def insert(self, tup): + def insert(self, tup) -> None: """ Inserts a node into the Priority Queue. @@ -168,7 +168,7 @@ def par(self, i): """ return math.floor(i / 2) - def swap(self, i, j): + def swap(self, i, j) -> None: """ Swaps array elements at indices i and j, update the pos{} @@ -189,7 +189,7 @@ def swap(self, i, j): self.array[i] = self.array[j] self.array[j] = temp - def decrease_key(self, tup, new_d): + def decrease_key(self, tup, new_d) -> None: """ Decrease the key value for a given tuple, assuming the new_d is at most old_d. @@ -232,7 +232,7 @@ def __init__(self, num): self.dist = [0] * self.num_nodes self.par = [-1] * self.num_nodes # To store the path - def add_edge(self, u, v, w): + def add_edge(self, u, v, w) -> None: """ Add edge going from node u to v and v to u with weight w: u (w)-> v, v (w) -> u @@ -255,7 +255,7 @@ def add_edge(self, u, v, w): else: self.adjList[v] = [(u, w)] - def show_graph(self): + def show_graph(self) -> None: """ Show the graph: u -> v(w) @@ -274,7 +274,7 @@ def show_graph(self): for u in self.adjList: print(u, "->", " -> ".join(str(f"{v}({w})") for v, w in self.adjList[u])) - def dijkstra(self, src): + def dijkstra(self, src) -> None: """ Dijkstra algorithm @@ -377,7 +377,7 @@ def dijkstra(self, src): # Show the shortest distances from src self.show_distances(src) - def show_distances(self, src): + def show_distances(self, src) -> None: """ Show the distances from src to all other nodes in a graph @@ -391,7 +391,7 @@ def show_distances(self, src): for u in range(self.num_nodes): print(f"Node {u} has distance: {self.dist[u]}") - def show_path(self, src, dest): + def show_path(self, src, dest) -> None: """ Shows the shortest path from src to dest. WARNING: Use it *after* calling dijkstra. diff --git a/graphs/dinic.py b/graphs/dinic.py index 7919e6bc060a..bfc3269e2616 100644 --- a/graphs/dinic.py +++ b/graphs/dinic.py @@ -14,7 +14,7 @@ def __init__(self, n): through that edge ... """ - def add_edge(self, a, b, c, rcap=0): + def add_edge(self, a, b, c, rcap=0) -> None: self.adj[a].append([b, len(self.adj[b]), c, 0]) self.adj[b].append([a, len(self.adj[a]) - 1, rcap, 0]) diff --git a/graphs/directed_and_undirected_weighted_graph.py b/graphs/directed_and_undirected_weighted_graph.py index 8ca645fdace8..deb5af3bcb17 100644 --- a/graphs/directed_and_undirected_weighted_graph.py +++ b/graphs/directed_and_undirected_weighted_graph.py @@ -13,7 +13,7 @@ def __init__(self): # adding vertices and edges # adding the weight is optional # handles repetition - def add_pair(self, u, v, w=1): + def add_pair(self, u, v, w=1) -> None: if self.graph.get(u): if self.graph[u].count([w, v]) == 0: self.graph[u].append([w, v]) @@ -26,7 +26,7 @@ def all_nodes(self): return list(self.graph) # handles if the input does not exist - def remove_pair(self, u, v): + def remove_pair(self, u, v) -> None: if self.graph.get(u): for _ in self.graph[u]: if _[1] == v: @@ -73,7 +73,7 @@ def dfs(self, s=-2, d=-1): # c is the count of nodes you want and if you leave it or pass -1 to the function # the count will be random from 10 to 10000 - def fill_graph_randomly(self, c=-1): + def fill_graph_randomly(self, c=-1) -> None: if c == -1: c = floor(random() * 10000) + 10 for i in range(c): @@ -196,7 +196,7 @@ def cycle_nodes(self): if len(stack) == 0: return list(anticipating_nodes) - def has_cycle(self): + def has_cycle(self) -> bool | None: stack = [] visited = [] s = next(iter(self.graph)) @@ -268,7 +268,7 @@ def __init__(self): # adding vertices and edges # adding the weight is optional # handles repetition - def add_pair(self, u, v, w=1): + def add_pair(self, u, v, w=1) -> None: # check if the u exists if self.graph.get(u): # if there already is a edge @@ -287,7 +287,7 @@ def add_pair(self, u, v, w=1): self.graph[v] = [[w, u]] # handles if the input does not exist - def remove_pair(self, u, v): + def remove_pair(self, u, v) -> None: if self.graph.get(u): for _ in self.graph[u]: if _[1] == v: @@ -339,7 +339,7 @@ def dfs(self, s=-2, d=-1): # c is the count of nodes you want and if you leave it or pass -1 to the function # the count will be random from 10 to 10000 - def fill_graph_randomly(self, c=-1): + def fill_graph_randomly(self, c=-1) -> None: if c == -1: c = floor(random() * 10000) + 10 for i in range(c): @@ -421,7 +421,7 @@ def cycle_nodes(self): if len(stack) == 0: return list(anticipating_nodes) - def has_cycle(self): + def has_cycle(self) -> bool | None: stack = [] visited = [] s = next(iter(self.graph)) diff --git a/graphs/edmonds_karp_multiple_source_and_sink.py b/graphs/edmonds_karp_multiple_source_and_sink.py index 5c774f4b812b..014b79fb35e9 100644 --- a/graphs/edmonds_karp_multiple_source_and_sink.py +++ b/graphs/edmonds_karp_multiple_source_and_sink.py @@ -53,7 +53,7 @@ def find_maximum_flow(self): self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() - def set_maximum_flow_algorithm(self, algorithm): + def set_maximum_flow_algorithm(self, algorithm) -> None: self.maximum_flow_algorithm = algorithm(self) @@ -68,7 +68,7 @@ def __init__(self, flow_network): self.graph = flow_network.graph self.executed = False - def execute(self): + def execute(self) -> None: if not self.executed: self._algorithm() self.executed = True @@ -132,7 +132,7 @@ def _algorithm(self): self.maximum_flow = sum(self.preflow[self.source_index]) - def process_vertex(self, vertex_index): + def process_vertex(self, vertex_index) -> None: while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count): # if it's neighbour and current vertex is higher @@ -146,7 +146,7 @@ def process_vertex(self, vertex_index): self.relabel(vertex_index) - def push(self, from_index, to_index): + def push(self, from_index, to_index) -> None: preflow_delta = min( self.excesses[from_index], self.graph[from_index][to_index] - self.preflow[from_index][to_index], @@ -156,7 +156,7 @@ def push(self, from_index, to_index): self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta - def relabel(self, vertex_index): + def relabel(self, vertex_index) -> None: min_height = None for to_index in range(self.verticies_count): if ( diff --git a/graphs/eulerian_path_and_circuit_for_undirected_graph.py b/graphs/eulerian_path_and_circuit_for_undirected_graph.py index 5b146eaa845b..c0ac638aa957 100644 --- a/graphs/eulerian_path_and_circuit_for_undirected_graph.py +++ b/graphs/eulerian_path_and_circuit_for_undirected_graph.py @@ -32,7 +32,7 @@ def check_circuit_or_path(graph, max_node): return 3, odd_node -def check_euler(graph, max_node): +def check_euler(graph, max_node) -> None: visited_edge = [[False for _ in range(max_node + 1)] for _ in range(max_node + 1)] check, odd_node = check_circuit_or_path(graph, max_node) if check == 3: @@ -49,7 +49,7 @@ def check_euler(graph, max_node): print(path) -def main(): +def main() -> None: g1 = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} g2 = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} g3 = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} diff --git a/graphs/even_tree.py b/graphs/even_tree.py index 7d47899527a7..945c1ba8c05e 100644 --- a/graphs/even_tree.py +++ b/graphs/even_tree.py @@ -30,7 +30,7 @@ def dfs(start: int) -> int: return ret -def even_tree(): +def even_tree() -> None: """ 2 1 3 1 diff --git a/graphs/frequent_pattern_graph_miner.py b/graphs/frequent_pattern_graph_miner.py index f8da73f3438e..913fedb89c24 100644 --- a/graphs/frequent_pattern_graph_miner.py +++ b/graphs/frequent_pattern_graph_miner.py @@ -127,7 +127,7 @@ def print_all() -> None: print(edge_list) -def create_edge(nodes, graph, cluster, c1): +def create_edge(nodes, graph, cluster, c1) -> None: """ create edge between the nodes """ @@ -169,7 +169,7 @@ def construct_graph(cluster, nodes): return graph -def my_dfs(graph, start, end, path=None): +def my_dfs(graph, start, end, path=None) -> None: """ find different DFS walk from given node to Header node """ @@ -181,7 +181,7 @@ def my_dfs(graph, start, end, path=None): my_dfs(graph, tuple(node), end, path) -def find_freq_subgraph_given_support(s, cluster, graph): +def find_freq_subgraph_given_support(s, cluster, graph) -> None: """ find edges of multiple frequent subgraphs """ @@ -206,7 +206,7 @@ def freq_subgraphs_edge_list(paths): return freq_sub_el -def preprocess(edge_array): +def preprocess(edge_array) -> None: """ Preprocess the edge array >>> preprocess([['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'bh-e12', diff --git a/graphs/g_topological_sort.py b/graphs/g_topological_sort.py index 77543d51f61d..c6b24fa83919 100644 --- a/graphs/g_topological_sort.py +++ b/graphs/g_topological_sort.py @@ -18,7 +18,7 @@ stack = [] -def print_stack(stack, clothes): +def print_stack(stack, clothes) -> None: order = 1 while stack: current_clothing = stack.pop() @@ -26,7 +26,7 @@ def print_stack(stack, clothes): order += 1 -def depth_first_search(u, visited, graph): +def depth_first_search(u, visited, graph) -> None: visited[u] = 1 for v in graph[u]: if not visited[v]: @@ -35,7 +35,7 @@ def depth_first_search(u, visited, graph): stack.append(u) -def topological_sort(graph, visited): +def topological_sort(graph, visited) -> None: for v in range(len(graph)): if not visited[v]: depth_first_search(v, visited, graph) diff --git a/graphs/kahns_algorithm_long.py b/graphs/kahns_algorithm_long.py index 1f16b90c0745..b214d93c034b 100644 --- a/graphs/kahns_algorithm_long.py +++ b/graphs/kahns_algorithm_long.py @@ -1,5 +1,5 @@ # Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm -def longest_distance(graph): +def longest_distance(graph) -> None: indegree = [0] * len(graph) queue = [] long_dist = [1] * len(graph) diff --git a/graphs/minimum_spanning_tree_boruvka.py b/graphs/minimum_spanning_tree_boruvka.py index f234d65ab765..a4ed0e07b042 100644 --- a/graphs/minimum_spanning_tree_boruvka.py +++ b/graphs/minimum_spanning_tree_boruvka.py @@ -8,7 +8,7 @@ def __init__(self): self.num_edges = 0 self.adjacency = {} - def add_vertex(self, vertex): + def add_vertex(self, vertex) -> None: """ Adds a vertex to the graph @@ -17,7 +17,7 @@ def add_vertex(self, vertex): self.adjacency[vertex] = {} self.num_vertices += 1 - def add_edge(self, head, tail, weight): + def add_edge(self, head, tail, weight) -> None: """ Adds an edge to the graph @@ -32,7 +32,7 @@ def add_edge(self, head, tail, weight): self.adjacency[head][tail] = weight self.adjacency[tail][head] = weight - def distinct_weight(self): + def distinct_weight(self) -> None: """ For Boruvks's algorithm the weights should be distinct Converts the weights to be distinct diff --git a/graphs/minimum_spanning_tree_prims.py b/graphs/minimum_spanning_tree_prims.py index d0b45d7ef139..2043279a5b73 100644 --- a/graphs/minimum_spanning_tree_prims.py +++ b/graphs/minimum_spanning_tree_prims.py @@ -9,10 +9,10 @@ def __init__(self): def get_position(self, vertex): return self.node_position[vertex] - def set_position(self, vertex, pos): + def set_position(self, vertex, pos) -> None: self.node_position[vertex] = pos - def top_to_bottom(self, heap, start, size, positions): + def top_to_bottom(self, heap, start, size, positions) -> None: if start > size // 2 - 1: return else: @@ -39,7 +39,7 @@ def top_to_bottom(self, heap, start, size, positions): self.top_to_bottom(heap, smallest_child, size, positions) # Update function if value of any node in min-heap decreases - def bottom_to_top(self, val, index, heap, position): + def bottom_to_top(self, val, index, heap, position) -> None: temp = position[index] while index != 0: @@ -60,7 +60,7 @@ def bottom_to_top(self, val, index, heap, position): position[0] = temp self.set_position(temp, 0) - def heapify(self, heap, positions): + def heapify(self, heap, positions) -> None: start = len(heap) // 2 - 1 for i in range(start, -1, -1): self.top_to_bottom(heap, i, len(heap), positions) diff --git a/graphs/multi_heuristic_astar.py b/graphs/multi_heuristic_astar.py index 38b07e1ca675..d930150a0338 100644 --- a/graphs/multi_heuristic_astar.py +++ b/graphs/multi_heuristic_astar.py @@ -20,7 +20,7 @@ def minkey(self): def empty(self): return len(self.elements) == 0 - def put(self, item, priority): + def put(self, item, priority) -> None: if item not in self.set: heapq.heappush(self.elements, (priority, item)) self.set.add(item) @@ -36,7 +36,7 @@ def put(self, item, priority): for pro, xxx in temp: heapq.heappush(self.elements, (pro, xxx)) - def remove_element(self, item): + def remove_element(self, item) -> None: if item in self.set: self.set.remove(item) temp = [] @@ -78,7 +78,7 @@ def key(start: TPos, i: int, goal: TPos, g_function: dict[TPos, float]): return ans -def do_something(back_pointer, goal, start): +def do_something(back_pointer, goal, start) -> None: grid = np.char.chararray((n, n)) for i in range(n): for j in range(n): @@ -120,7 +120,7 @@ def do_something(back_pointer, goal, start): sys.exit() -def valid(p: TPos): +def valid(p: TPos) -> bool: if p[0] < 0 or p[0] > n - 1: return False return not (p[1] < 0 or p[1] > n - 1) @@ -135,7 +135,7 @@ def expand_state( close_list_inad, open_list, back_pointer, -): +) -> None: for itera in range(n_heuristic): open_list[itera].remove_element(s) # print("s", s) @@ -233,7 +233,7 @@ def make_common_ground(): t = 1 -def multi_a_star(start: TPos, goal: TPos, n_heuristic: int): +def multi_a_star(start: TPos, goal: TPos, n_heuristic: int) -> None: g_function = {start: 0, goal: float("inf")} back_pointer = {start: -1, goal: -1} open_list = [] diff --git a/graphs/page_rank.py b/graphs/page_rank.py index 56274bddcbb7..21eb3bcd5f2b 100644 --- a/graphs/page_rank.py +++ b/graphs/page_rank.py @@ -21,10 +21,10 @@ def __init__(self, name): self.inbound = [] self.outbound = [] - def add_inbound(self, node): + def add_inbound(self, node) -> None: self.inbound.append(node) - def add_outbound(self, node): + def add_outbound(self, node) -> None: self.outbound.append(node) def __repr__(self): @@ -55,7 +55,7 @@ def page_rank(nodes, max_iter=100, d=0.85, tol=1e-8): return ranks -def main(): +def main() -> None: names = list(input("Enter Names of the Nodes: ").split()) nodes = [Node(name) for name in names] diff --git a/graphs/prim.py b/graphs/prim.py index 5b3ce04441ec..4989e46f1e12 100644 --- a/graphs/prim.py +++ b/graphs/prim.py @@ -35,16 +35,16 @@ def __repr__(self): """Return the vertex id.""" return self.id - def add_neighbor(self, vertex): + def add_neighbor(self, vertex) -> None: """Add a pointer to a vertex at neighbor's list.""" self.neighbors.append(vertex) - def add_edge(self, vertex, weight): + def add_edge(self, vertex, weight) -> None: """Destination vertex and weight.""" self.edges[vertex.id] = weight -def connect(graph, a, b, edge): +def connect(graph, a, b, edge) -> None: # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) diff --git a/graphs/scc_kosaraju.py b/graphs/scc_kosaraju.py index 39211c64b687..2494a2bb3c34 100644 --- a/graphs/scc_kosaraju.py +++ b/graphs/scc_kosaraju.py @@ -1,7 +1,7 @@ from __future__ import annotations -def dfs(u): +def dfs(u) -> None: global graph, reversed_graph, scc, component, visit, stack if visit[u]: return @@ -11,7 +11,7 @@ def dfs(u): stack.append(u) -def dfs2(u): +def dfs2(u) -> None: global graph, reversed_graph, scc, component, visit, stack if visit[u]: return diff --git a/graphs/tests/test_johnson.py b/graphs/tests/test_johnson.py index e149aac85d0f..52d6a78a5983 100644 --- a/graphs/tests/test_johnson.py +++ b/graphs/tests/test_johnson.py @@ -5,7 +5,7 @@ from graphs.johnson import johnson -def test_johnson_basic(): +def test_johnson_basic() -> None: g = { 0: [(1, 3), (2, 8), (4, -4)], 1: [(3, 1), (4, 7)], @@ -18,7 +18,7 @@ def test_johnson_basic(): assert math.isclose(dist[3][2], -5.0, abs_tol=1e-9) -def test_johnson_negative_cycle(): +def test_johnson_negative_cycle() -> None: g2 = {0: [(1, 1)], 1: [(0, -3)]} with pytest.raises(ValueError): johnson(g2) diff --git a/graphs/tests/test_min_spanning_tree_kruskal.py b/graphs/tests/test_min_spanning_tree_kruskal.py index d6df242ec6d1..96f869260b3b 100644 --- a/graphs/tests/test_min_spanning_tree_kruskal.py +++ b/graphs/tests/test_min_spanning_tree_kruskal.py @@ -1,7 +1,7 @@ from graphs.minimum_spanning_tree_kruskal import kruskal -def test_kruskal_successful_result(): +def test_kruskal_successful_result() -> None: num_nodes = 9 edges = [ [0, 1, 4], diff --git a/graphs/tests/test_min_spanning_tree_prim.py b/graphs/tests/test_min_spanning_tree_prim.py index 66e5706dadb1..b53a8396fcf2 100644 --- a/graphs/tests/test_min_spanning_tree_prim.py +++ b/graphs/tests/test_min_spanning_tree_prim.py @@ -3,7 +3,7 @@ from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst -def test_prim_successful_result(): +def test_prim_successful_result() -> None: num_nodes, num_edges = 9, 14 # noqa: F841 edges = [ [0, 1, 4], diff --git a/hashes/chaos_machine.py b/hashes/chaos_machine.py index d2fde2f5e371..2e62ac3ba4bb 100644 --- a/hashes/chaos_machine.py +++ b/hashes/chaos_machine.py @@ -13,7 +13,7 @@ machine_time = 0 -def push(seed): +def push(seed) -> None: global buffer_space, params_space, machine_time, K, m, t # Choosing Dynamical Systems (All) @@ -72,7 +72,7 @@ def xorshift(x, y): return xorshift(x, y) % 0xFFFFFFFF -def reset(): +def reset() -> None: global buffer_space, params_space, machine_time, K, m, t buffer_space = K diff --git a/hashes/enigma_machine.py b/hashes/enigma_machine.py index 0da8e4113de9..8a61332da00d 100644 --- a/hashes/enigma_machine.py +++ b/hashes/enigma_machine.py @@ -7,7 +7,7 @@ gear_one_pos = gear_two_pos = gear_three_pos = 0 -def rotator(): +def rotator() -> None: global gear_one_pos global gear_two_pos global gear_three_pos @@ -27,7 +27,7 @@ def rotator(): gear_three_pos += 1 -def engine(input_character): +def engine(input_character) -> None: target = alphabets.index(input_character) target = gear_one[target] target = gear_two[target] diff --git a/hashes/sha1.py b/hashes/sha1.py index 75a1423e9b5f..77388222c1db 100644 --- a/hashes/sha1.py +++ b/hashes/sha1.py @@ -130,12 +130,12 @@ def final_hash(self): return ("{:08x}" * 5).format(*self.h) -def test_sha1_hash(): +def test_sha1_hash() -> None: msg = b"Test String" assert SHA1Hash(msg).final_hash() == hashlib.sha1(msg).hexdigest() # noqa: S324 -def main(): +def main() -> None: """ Provides option 'string' or 'file' to take input and prints the calculated SHA1 hash. unittest.main() has been commented out because we probably don't want to run diff --git a/knapsack/tests/test_greedy_knapsack.py b/knapsack/tests/test_greedy_knapsack.py index 7ebaddd3c99e..5bcbd8d2e611 100644 --- a/knapsack/tests/test_greedy_knapsack.py +++ b/knapsack/tests/test_greedy_knapsack.py @@ -10,7 +10,7 @@ class TestClass(unittest.TestCase): Test cases for knapsack """ - def test_sorted(self): + def test_sorted(self) -> None: """ kp.calc_profit takes the required argument (profit, weight, max_weight) and returns whether the answer matches to the expected ones @@ -20,7 +20,7 @@ def test_sorted(self): max_weight = 100 assert kp.calc_profit(profit, weight, max_weight) == 210 - def test_negative_max_weight(self): + def test_negative_max_weight(self) -> None: """ Returns ValueError for any negative max_weight value :return: ValueError @@ -30,7 +30,7 @@ def test_negative_max_weight(self): # max_weight = -15 pytest.raises(ValueError, match=r"max_weight must greater than zero.") - def test_negative_profit_value(self): + def test_negative_profit_value(self) -> None: """ Returns ValueError for any negative profit value in the list :return: ValueError @@ -40,7 +40,7 @@ def test_negative_profit_value(self): # max_weight = 15 pytest.raises(ValueError, match=r"Weight can not be negative.") - def test_negative_weight_value(self): + def test_negative_weight_value(self) -> None: """ Returns ValueError for any negative weight value in the list :return: ValueError @@ -50,7 +50,7 @@ def test_negative_weight_value(self): # max_weight = 15 pytest.raises(ValueError, match=r"Profit can not be negative.") - def test_null_max_weight(self): + def test_null_max_weight(self) -> None: """ Returns ValueError for any zero max_weight value :return: ValueError @@ -60,7 +60,7 @@ def test_null_max_weight(self): # max_weight = null pytest.raises(ValueError, match=r"max_weight must greater than zero.") - def test_unequal_list_length(self): + def test_unequal_list_length(self) -> None: """ Returns IndexError if length of lists (profit and weight) are unequal. :return: IndexError diff --git a/knapsack/tests/test_knapsack.py b/knapsack/tests/test_knapsack.py index 80378aae4579..0bd2814e2659 100644 --- a/knapsack/tests/test_knapsack.py +++ b/knapsack/tests/test_knapsack.py @@ -13,7 +13,7 @@ class Test(unittest.TestCase): - def test_base_case(self): + def test_base_case(self) -> None: """ test for the base case """ @@ -28,7 +28,7 @@ def test_base_case(self): c = len(val) assert k.knapsack(cap, w, val, c) == 0 - def test_easy_case(self): + def test_easy_case(self) -> None: """ test for the easy case """ @@ -38,7 +38,7 @@ def test_easy_case(self): c = len(val) assert k.knapsack(cap, w, val, c) == 5 - def test_knapsack(self): + def test_knapsack(self) -> None: """ test for the knapsack """ @@ -48,7 +48,7 @@ def test_knapsack(self): c = len(val) assert k.knapsack(cap, w, val, c) == 220 - def test_knapsack_repetition(self): + def test_knapsack_repetition(self) -> None: """ test for the knapsack repetition """ diff --git a/machine_learning/astar.py b/machine_learning/astar.py index a5859e51fe70..4f8f0114338f 100644 --- a/machine_learning/astar.py +++ b/machine_learning/astar.py @@ -39,7 +39,7 @@ def __init__(self): def __eq__(self, cell): return self.position == cell.position - def showcell(self): + def showcell(self) -> None: print(self.position) @@ -55,7 +55,7 @@ def __init__(self, world_size=(5, 5)): self.world_x_limit = world_size[0] self.world_y_limit = world_size[1] - def show(self): + def show(self) -> None: print(self.w) def get_neighbours(self, cell): diff --git a/machine_learning/decision_tree.py b/machine_learning/decision_tree.py index b4df64796bb1..c5021fa62880 100644 --- a/machine_learning/decision_tree.py +++ b/machine_learning/decision_tree.py @@ -42,7 +42,7 @@ def mean_squared_error(self, labels, prediction): return np.mean((labels - prediction) ** 2) - def train(self, x, y): + def train(self, x, y) -> None: """ train: @param x: a one-dimensional numpy array @@ -173,7 +173,7 @@ def helper_mean_squared_error_test(labels, prediction): return float(squared_error_sum / labels.size) -def main(): +def main() -> None: """ In this demonstration we're generating a sample data set from the sin function in numpy. We then train a decision tree on the data set and use the decision tree to diff --git a/machine_learning/gaussian_naive_bayes.py b/machine_learning/gaussian_naive_bayes.py index 6af4b210ba53..f6ff682402b3 100644 --- a/machine_learning/gaussian_naive_bayes.py +++ b/machine_learning/gaussian_naive_bayes.py @@ -7,7 +7,7 @@ from sklearn.naive_bayes import GaussianNB -def main(): +def main() -> None: """ Gaussian Naive Bayes Example using sklearn function. Iris type dataset is used to demonstrate algorithm. diff --git a/machine_learning/gradient_boosting_regressor.py b/machine_learning/gradient_boosting_regressor.py index 40deb11ebe6b..0f2dadb32c5f 100644 --- a/machine_learning/gradient_boosting_regressor.py +++ b/machine_learning/gradient_boosting_regressor.py @@ -16,7 +16,7 @@ from sklearn.model_selection import train_test_split -def main(): +def main() -> None: # loading the dataset from sklearn df = load_diabetes() print(df.keys()) diff --git a/machine_learning/gradient_descent.py b/machine_learning/gradient_descent.py index 4c92f293dfbd..75951571400c 100644 --- a/machine_learning/gradient_descent.py +++ b/machine_learning/gradient_descent.py @@ -132,7 +132,7 @@ def get_cost_derivative(index): return cost_derivative_value -def run_gradient_descent(): +def run_gradient_descent() -> None: global parameter_vector # Tune these values to set a tolerance value for predicted output absolute_error_limit = 0.000002 @@ -157,7 +157,7 @@ def run_gradient_descent(): print(("Number of iterations:", j)) -def test_gradient_descent(): +def test_gradient_descent() -> None: for i in range(len(test_data)): print(("Actual output value:", output(i, "test"))) print(("Hypothesis output:", calculate_hypothesis_value(i, "test"))) diff --git a/machine_learning/k_means_clust.py b/machine_learning/k_means_clust.py index d553d2a1e0e5..19e510b966b6 100644 --- a/machine_learning/k_means_clust.py +++ b/machine_learning/k_means_clust.py @@ -146,7 +146,7 @@ def compute_heterogeneity(data, k, centroids, cluster_assignment): return heterogeneity -def plot_heterogeneity(heterogeneity, k): +def plot_heterogeneity(heterogeneity, k) -> None: plt.figure(figsize=(7, 4)) plt.plot(heterogeneity, linewidth=4) plt.xlabel("# Iterations") @@ -156,7 +156,7 @@ def plot_heterogeneity(heterogeneity, k): plt.show() -def plot_kmeans(data, centroids, cluster_assignment): +def plot_kmeans(data, centroids, cluster_assignment) -> None: ax = plt.axes(projection="3d") ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=cluster_assignment, cmap="viridis") ax.scatter( diff --git a/machine_learning/linear_discriminant_analysis.py b/machine_learning/linear_discriminant_analysis.py index de2d1de46ba1..1d26ffd3efae 100644 --- a/machine_learning/linear_discriminant_analysis.py +++ b/machine_learning/linear_discriminant_analysis.py @@ -280,7 +280,7 @@ def valid_input[num]( # Main Function -def main(): +def main() -> None: """This function starts execution phase""" while True: print(" Linear Discriminant Analysis ".center(50, "*")) diff --git a/machine_learning/linear_regression.py b/machine_learning/linear_regression.py index 7ae60c1f2185..fb5d0da5e335 100644 --- a/machine_learning/linear_regression.py +++ b/machine_learning/linear_regression.py @@ -122,7 +122,7 @@ def mean_absolute_error(predicted_y, original_y): return total / len(original_y) -def main(): +def main() -> None: """Driver function""" data = collect_dataset() diff --git a/machine_learning/random_forest_classifier.py b/machine_learning/random_forest_classifier.py index d77c37aadb87..4b3334b1cdb6 100644 --- a/machine_learning/random_forest_classifier.py +++ b/machine_learning/random_forest_classifier.py @@ -7,7 +7,7 @@ from sklearn.model_selection import train_test_split -def main(): +def main() -> None: """ Random Forest Classifier Example using sklearn function. Iris type dataset is used to demonstrate algorithm. diff --git a/machine_learning/random_forest_regressor.py b/machine_learning/random_forest_regressor.py index 1be8d6240594..2e98ac4c19de 100644 --- a/machine_learning/random_forest_regressor.py +++ b/machine_learning/random_forest_regressor.py @@ -6,7 +6,7 @@ from sklearn.model_selection import train_test_split -def main(): +def main() -> None: """ Random Forest Regressor Example using sklearn function. The diabetes dataset is used to demonstrate the algorithm. diff --git a/machine_learning/sequential_minimum_optimization.py b/machine_learning/sequential_minimum_optimization.py index e96f06d6f080..900d06941973 100644 --- a/machine_learning/sequential_minimum_optimization.py +++ b/machine_learning/sequential_minimum_optimization.py @@ -75,7 +75,7 @@ def __init__( self.choose_alpha = self._choose_alphas() # Calculate alphas using SMO algorithm - def fit(self): + def fit(self) -> None: k = self._k state = None while True: @@ -447,7 +447,7 @@ def call_func(*args, **kwargs): @count_time -def test_cancer_data(): +def test_cancer_data() -> None: print("Hello!\nStart test SVM using the SMO algorithm!") # 0: download dataset and load into pandas' dataframe if not os.path.exists(r"cancer_data.csv"): @@ -502,7 +502,7 @@ def test_cancer_data(): print(f"Rough Accuracy: {score / test_tags.shape[0]}") -def test_demonstration(): +def test_demonstration() -> None: # change stdout print("\nStarting plot, please wait!") sys.stdout = open(os.devnull, "w") @@ -524,7 +524,7 @@ def test_demonstration(): print("Plot done!") -def test_linear_kernel(ax, cost): +def test_linear_kernel(ax, cost) -> None: train_x, train_y = make_blobs( n_samples=500, centers=2, n_features=2, random_state=1 ) @@ -544,7 +544,7 @@ def test_linear_kernel(ax, cost): plot_partition_boundary(mysvm, train_data, ax=ax) -def test_rbf_kernel(ax, cost): +def test_rbf_kernel(ax, cost) -> None: train_x, train_y = make_circles( n_samples=500, noise=0.1, factor=0.1, random_state=1 ) @@ -566,7 +566,7 @@ def test_rbf_kernel(ax, cost): def plot_partition_boundary( model, train_data, ax, resolution=100, colors=("b", "k", "r") -): +) -> None: """ We cannot get the optimal w of our kernel SVM model, which is different from a linear SVM. For this reason, we generate randomly distributed points with high diff --git a/maths/abs.py b/maths/abs.py index b357e98d8680..1a7e04dd00e1 100644 --- a/maths/abs.py +++ b/maths/abs.py @@ -71,7 +71,7 @@ def abs_max_sort(x: list[int]) -> int: return sorted(x, key=abs)[-1] -def test_abs_val(): +def test_abs_val() -> None: """ >>> test_abs_val() """ diff --git a/maths/average_median.py b/maths/average_median.py index f24e525736b3..e929a7766d26 100644 --- a/maths/average_median.py +++ b/maths/average_median.py @@ -31,7 +31,7 @@ def median(nums: list) -> int | float: ) -def main(): +def main() -> None: import doctest doctest.testmod() diff --git a/maths/collatz_sequence.py b/maths/collatz_sequence.py index b00dca8d70b7..1e075f880f95 100644 --- a/maths/collatz_sequence.py +++ b/maths/collatz_sequence.py @@ -56,7 +56,7 @@ def collatz_sequence(n: int) -> Generator[int]: yield n -def main(): +def main() -> None: n = int(input("Your number: ")) sequence = tuple(collatz_sequence(n)) print(sequence) diff --git a/maths/entropy.py b/maths/entropy.py index b816f1d193f7..a72c54b626c3 100644 --- a/maths/entropy.py +++ b/maths/entropy.py @@ -108,7 +108,7 @@ def analyze_text(text: str) -> tuple[dict, dict]: return single_char_strings, two_char_strings -def main(): +def main() -> None: import doctest doctest.testmod() diff --git a/maths/extended_euclidean_algorithm.py b/maths/extended_euclidean_algorithm.py index c54909e19101..b3b279581f38 100644 --- a/maths/extended_euclidean_algorithm.py +++ b/maths/extended_euclidean_algorithm.py @@ -71,7 +71,7 @@ def extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]: return old_coeff_a, old_coeff_b -def main(): +def main() -> int: """Call Extended Euclidean Algorithm.""" if len(sys.argv) < 3: print("2 integer arguments required") diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index ce0abc664cf9..4b6bab8941dc 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -60,7 +60,7 @@ def gcd_by_iterative(x: int, y: int) -> int: return abs(x) -def main(): +def main() -> None: """ Call Greatest Common Divisor function. """ diff --git a/maths/karatsuba.py b/maths/karatsuba.py index 0e063fb44b83..0beed90e2033 100644 --- a/maths/karatsuba.py +++ b/maths/karatsuba.py @@ -24,7 +24,7 @@ def karatsuba(a: int, b: int) -> int: return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) -def main(): +def main() -> None: print(karatsuba(15463, 23489)) diff --git a/maths/least_common_multiple.py b/maths/least_common_multiple.py index a5c4bf8e3625..9de815ac85bd 100644 --- a/maths/least_common_multiple.py +++ b/maths/least_common_multiple.py @@ -34,7 +34,7 @@ def least_common_multiple_fast(first_num: int, second_num: int) -> int: return first_num // greatest_common_divisor(first_num, second_num) * second_num -def benchmark(): +def benchmark() -> None: setup = ( "from __main__ import least_common_multiple_slow, least_common_multiple_fast" ) @@ -62,7 +62,7 @@ class TestLeastCommonMultiple(unittest.TestCase): ) expected_results = (20, 195, 124, 210, 1462, 60, 300, 50, 18) - def test_lcm_function(self): + def test_lcm_function(self) -> None: for i, (first_num, second_num) in enumerate(self.test_inputs): slow_result = least_common_multiple_slow(first_num, second_num) fast_result = least_common_multiple_fast(first_num, second_num) diff --git a/maths/modular_exponential.py b/maths/modular_exponential.py index a27e29ebc02a..eadde7e793d8 100644 --- a/maths/modular_exponential.py +++ b/maths/modular_exponential.py @@ -32,7 +32,7 @@ def modular_exponential(base: int, power: int, mod: int): return result -def main(): +def main() -> None: """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) diff --git a/maths/numerical_analysis/simpson_rule.py b/maths/numerical_analysis/simpson_rule.py index e75fb557a2f5..66aff65482d7 100644 --- a/maths/numerical_analysis/simpson_rule.py +++ b/maths/numerical_analysis/simpson_rule.py @@ -70,7 +70,7 @@ def f(x): # enter your function here return y -def main(): +def main() -> None: a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # number of steps or resolution diff --git a/maths/prime_check.py b/maths/prime_check.py index a757c4108f24..32d4f5d6e704 100644 --- a/maths/prime_check.py +++ b/maths/prime_check.py @@ -58,7 +58,7 @@ def is_prime(number: int) -> bool: class Test(unittest.TestCase): - def test_primes(self): + def test_primes(self) -> None: assert is_prime(2) assert is_prime(3) assert is_prime(5) @@ -70,7 +70,7 @@ def test_primes(self): assert is_prime(23) assert is_prime(29) - def test_not_primes(self): + def test_not_primes(self) -> None: with pytest.raises(ValueError): is_prime(-19) assert not is_prime(0), ( diff --git a/maths/prime_numbers.py b/maths/prime_numbers.py index 5ad12baf3dc3..940b6847e0b0 100644 --- a/maths/prime_numbers.py +++ b/maths/prime_numbers.py @@ -90,7 +90,7 @@ def fast_primes(max_n: int) -> Generator[int]: yield i -def benchmark(): +def benchmark() -> None: """ Let's benchmark our functions side-by-side... """ diff --git a/maths/quadratic_equations_complex_numbers.py b/maths/quadratic_equations_complex_numbers.py index 1035171e4ec3..6e6760216590 100644 --- a/maths/quadratic_equations_complex_numbers.py +++ b/maths/quadratic_equations_complex_numbers.py @@ -29,7 +29,7 @@ def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: ) -def main(): +def main() -> None: solution1, solution2 = quadratic_roots(a=5, b=6, c=1) print(f"The solutions are: {solution1} and {solution2}") diff --git a/maths/special_numbers/armstrong_numbers.py b/maths/special_numbers/armstrong_numbers.py index a3cb69b814de..093ed017a6ed 100644 --- a/maths/special_numbers/armstrong_numbers.py +++ b/maths/special_numbers/armstrong_numbers.py @@ -82,7 +82,7 @@ def narcissistic_number(n: int) -> bool: return n == sum(int(i) ** expo for i in str(n)) -def main(): +def main() -> None: """ Request that user input an integer and tell them if it is Armstrong number. """ diff --git a/maths/test_factorial.py b/maths/test_factorial.py index 1795ebba194f..4fced2161110 100644 --- a/maths/test_factorial.py +++ b/maths/test_factorial.py @@ -11,30 +11,30 @@ @pytest.mark.parametrize("function", [factorial, factorial_recursive]) -def test_zero(function): +def test_zero(function) -> None: assert function(0) == 1 @pytest.mark.parametrize("function", [factorial, factorial_recursive]) -def test_positive_integers(function): +def test_positive_integers(function) -> None: assert function(1) == 1 assert function(5) == 120 assert function(7) == 5040 @pytest.mark.parametrize("function", [factorial, factorial_recursive]) -def test_large_number(function): +def test_large_number(function) -> None: assert function(10) == 3628800 @pytest.mark.parametrize("function", [factorial, factorial_recursive]) -def test_negative_number(function): +def test_negative_number(function) -> None: with pytest.raises(ValueError): function(-3) @pytest.mark.parametrize("function", [factorial, factorial_recursive]) -def test_float_number(function): +def test_float_number(function) -> None: with pytest.raises(ValueError): function(1.5) diff --git a/maths/trapezoidal_rule.py b/maths/trapezoidal_rule.py index 21b10b239b5f..69198559f234 100644 --- a/maths/trapezoidal_rule.py +++ b/maths/trapezoidal_rule.py @@ -79,7 +79,7 @@ def f(x): return x**2 -def main(): +def main() -> None: """ Main function to test the trapezoidal rule. :a: Lower bound of integration diff --git a/maths/volume.py b/maths/volume.py index f48d388b423e..3871d6b1d7c3 100644 --- a/maths/volume.py +++ b/maths/volume.py @@ -566,7 +566,7 @@ def vol_icosahedron(tri_side: float) -> float: return tri_side**3 * (3 + 5**0.5) * 5 / 12 -def main(): +def main() -> None: """Print the Results of Various Volume Calculations.""" print("Volumes:") print(f"Cube: {vol_cube(2) = }") # = 8 diff --git a/matrix/tests/test_matrix_operation.py b/matrix/tests/test_matrix_operation.py index 21ed7e371fd8..6c20bf722e17 100644 --- a/matrix/tests/test_matrix_operation.py +++ b/matrix/tests/test_matrix_operation.py @@ -35,7 +35,7 @@ @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) -def test_addition(mat1, mat2): +def test_addition(mat1, mat2) -> None: if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_addition.__name__} returned integer") with pytest.raises(TypeError): @@ -55,7 +55,7 @@ def test_addition(mat1, mat2): @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) -def test_subtraction(mat1, mat2): +def test_subtraction(mat1, mat2) -> None: if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_subtraction.__name__} returned integer") with pytest.raises(TypeError): @@ -75,7 +75,7 @@ def test_subtraction(mat1, mat2): @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) -def test_multiplication(mat1, mat2): +def test_multiplication(mat1, mat2) -> None: if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_multiplication.__name__} returned integer") with pytest.raises(TypeError): @@ -94,14 +94,14 @@ def test_multiplication(mat1, mat2): @pytest.mark.mat_ops -def test_scalar_multiply(): +def test_scalar_multiply() -> None: act = (3.5 * np.array(mat_a)).tolist() theo = matop.scalar_multiply(mat_a, 3.5) assert theo == act @pytest.mark.mat_ops -def test_identity(): +def test_identity() -> None: act = (np.identity(5)).tolist() theo = matop.identity(5) assert theo == act @@ -109,7 +109,7 @@ def test_identity(): @pytest.mark.mat_ops @pytest.mark.parametrize("mat", [mat_a, mat_b, mat_c, mat_d, mat_e, mat_f]) -def test_transpose(mat): +def test_transpose(mat) -> None: if (np.array(mat)).shape < (2, 2): logger.info(f"\n\t{test_transpose.__name__} returned integer") with pytest.raises(TypeError): diff --git a/neural_network/back_propagation_neural_network.py b/neural_network/back_propagation_neural_network.py index 182f759c5fc7..80266ce03ee6 100644 --- a/neural_network/back_propagation_neural_network.py +++ b/neural_network/back_propagation_neural_network.py @@ -50,7 +50,7 @@ def __init__( self.learn_rate = learning_rate self.is_input_layer = is_input_layer - def initializer(self, back_units): + def initializer(self, back_units) -> None: rng = np.random.default_rng() self.weight = np.asmatrix(rng.normal(0, 0.5, (self.units, back_units))) self.bias = np.asmatrix(rng.normal(0, 0.5, self.units)).T @@ -107,17 +107,17 @@ def __init__(self): self.fig_loss = plt.figure() self.ax_loss = self.fig_loss.add_subplot(1, 1, 1) - def add_layer(self, layer): + def add_layer(self, layer) -> None: self.layers.append(layer) - def build(self): + def build(self) -> None: for i, layer in enumerate(self.layers[:]): if i < 1: layer.is_input_layer = True else: layer.initializer(self.layers[i - 1].units) - def summary(self): + def summary(self) -> None: for i, layer in enumerate(self.layers[:]): print(f"------- layer {i} -------") print("weight.shape ", np.shape(layer.weight)) @@ -163,7 +163,7 @@ def cal_loss(self, ydata, ydata_): # vector (shape is the same as _ydata.shape) return self.loss, self.loss_gradient - def plot_loss(self): + def plot_loss(self) -> None: if self.ax_loss.lines: self.ax_loss.lines.remove(self.ax_loss.lines[0]) self.ax_loss.plot(self.train_mse, "r-") @@ -174,7 +174,7 @@ def plot_loss(self): plt.pause(0.1) -def example(): +def example() -> None: rng = np.random.default_rng() x = rng.normal(size=(10, 10)) y = np.asarray( diff --git a/neural_network/convolution_neural_network.py b/neural_network/convolution_neural_network.py index 6b1aa50c7981..68a0d146d5ed 100644 --- a/neural_network/convolution_neural_network.py +++ b/neural_network/convolution_neural_network.py @@ -52,7 +52,7 @@ def __init__( self.thre_bp2 = -2 * rng.random(self.num_bp2) + 1 self.thre_bp3 = -2 * rng.random(self.num_bp3) + 1 - def save_model(self, save_path): + def save_model(self, save_path) -> None: # save model dict with pickle model_dic = { "num_bp1": self.num_bp1, diff --git a/other/greedy.py b/other/greedy.py index 72e05f451fbb..df0b7019b4f1 100644 --- a/other/greedy.py +++ b/other/greedy.py @@ -39,7 +39,7 @@ def greedy(item, max_cost, key_func): return (result, total_value) -def test_greedy(): +def test_greedy() -> None: """ >>> food = ["Burger", "Pizza", "Coca Cola", "Rice", ... "Sambhar", "Chicken", "Fries", "Milk"] diff --git a/other/nested_brackets.py b/other/nested_brackets.py index 5760fa29b2fd..f78dcb31a766 100644 --- a/other/nested_brackets.py +++ b/other/nested_brackets.py @@ -61,7 +61,7 @@ def is_balanced(s: str) -> bool: return not stack # stack should be empty -def main(): +def main() -> None: s = input("Enter sequence of brackets: ") print(f"'{s}' is {'' if is_balanced(s) else 'not '}balanced.") diff --git a/other/password.py b/other/password.py index dff1316c049c..6b64bdb4d81a 100644 --- a/other/password.py +++ b/other/password.py @@ -80,7 +80,7 @@ def is_strong_password(password: str, min_length: int = 8) -> bool: return upper and lower and num and spec_char -def main(): +def main() -> None: length = int(input("Please indicate the max length of your password: ").strip()) chars_incl = input( "Please indicate the characters that must be in your password: " diff --git a/other/tower_of_hanoi.py b/other/tower_of_hanoi.py index 1fff45039891..f86173237628 100644 --- a/other/tower_of_hanoi.py +++ b/other/tower_of_hanoi.py @@ -1,4 +1,4 @@ -def move_tower(height, from_pole, to_pole, with_pole): +def move_tower(height, from_pole, to_pole, with_pole) -> None: """ >>> move_tower(3, 'A', 'B', 'C') moving disk from A to B @@ -15,11 +15,11 @@ def move_tower(height, from_pole, to_pole, with_pole): move_tower(height - 1, with_pole, to_pole, from_pole) -def move_disk(fp, tp): +def move_disk(fp, tp) -> None: print("moving disk from", fp, "to", tp) -def main(): +def main() -> None: height = int(input("Height of hanoi: ").strip()) move_tower(height, "A", "B", "C") diff --git a/project_euler/problem_054/test_poker_hand.py b/project_euler/problem_054/test_poker_hand.py index ba5e0c8a2643..dc436cf0b661 100644 --- a/project_euler/problem_054/test_poker_hand.py +++ b/project_euler/problem_054/test_poker_hand.py @@ -148,43 +148,43 @@ def generate_random_hands(number_of_hands: int = 100): @pytest.mark.parametrize(("hand", "expected"), TEST_FLUSH) -def test_hand_is_flush(hand, expected): +def test_hand_is_flush(hand, expected) -> None: assert PokerHand(hand)._is_flush() == expected @pytest.mark.parametrize(("hand", "expected"), TEST_STRAIGHT) -def test_hand_is_straight(hand, expected): +def test_hand_is_straight(hand, expected) -> None: assert PokerHand(hand)._is_straight() == expected @pytest.mark.parametrize(("hand", "expected", "card_values"), TEST_FIVE_HIGH_STRAIGHT) -def test_hand_is_five_high_straight(hand, expected, card_values): +def test_hand_is_five_high_straight(hand, expected, card_values) -> None: player = PokerHand(hand) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize(("hand", "expected"), TEST_KIND) -def test_hand_is_same_kind(hand, expected): +def test_hand_is_same_kind(hand, expected) -> None: assert PokerHand(hand)._is_same_kind() == expected @pytest.mark.parametrize(("hand", "expected"), TEST_TYPES) -def test_hand_values(hand, expected): +def test_hand_values(hand, expected) -> None: assert PokerHand(hand)._hand_type == expected @pytest.mark.parametrize(("hand", "other", "expected"), TEST_COMPARE) -def test_compare_simple(hand, other, expected): +def test_compare_simple(hand, other, expected) -> None: assert PokerHand(hand).compare_with(PokerHand(other)) == expected @pytest.mark.parametrize(("hand", "other", "expected"), generate_random_hands()) -def test_compare_random(hand, other, expected): +def test_compare_random(hand, other, expected) -> None: assert PokerHand(hand).compare_with(PokerHand(other)) == expected -def test_hand_sorted(): +def test_hand_sorted() -> None: poker_hands = [PokerHand(hand) for hand in SORTED_HANDS] list_copy = poker_hands.copy() shuffle(list_copy) @@ -193,14 +193,14 @@ def test_hand_sorted(): assert hand == poker_hands[index] -def test_custom_sort_five_high_straight(): +def test_custom_sort_five_high_straight() -> None: # Test that five high straights are compared correctly. pokerhands = [PokerHand("2D AC 3H 4H 5S"), PokerHand("2S 3H 4H 5S 6C")] pokerhands.sort(reverse=True) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" -def test_multiple_calls_five_high_straight(): +def test_multiple_calls_five_high_straight() -> None: # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. pokerhand = PokerHand("2C 4S AS 3D 5C") @@ -211,7 +211,7 @@ def test_multiple_calls_five_high_straight(): assert pokerhand._card_values == expected_card_values -def test_euler_project(): +def test_euler_project() -> None: # Problem number 54 from Project Euler # Testing from poker_hands.txt file answer = 0 diff --git a/project_euler/problem_551/sol1.py b/project_euler/problem_551/sol1.py index e13cf77a776d..afa1748fb7ac 100644 --- a/project_euler/problem_551/sol1.py +++ b/project_euler/problem_551/sol1.py @@ -145,7 +145,7 @@ def compute(a_i, k, i, n): return diff, i - start_i -def add(digits, k, addend): +def add(digits, k, addend) -> None: """ adds addend to digit array given in digits starting at index k diff --git a/searches/tabu_search.py b/searches/tabu_search.py index fd482a81224c..7eb81b89ebc7 100644 --- a/searches/tabu_search.py +++ b/searches/tabu_search.py @@ -250,7 +250,7 @@ def tabu_search( return best_solution_ever, best_cost -def main(args=None): +def main(args=None) -> None: dict_of_neighbours = generate_neighbours(args.File) first_solution, distance_of_first_solution = generate_first_solution( diff --git a/sorts/external_sort.py b/sorts/external_sort.py index cfddee4fe7f8..b4759a9f2295 100644 --- a/sorts/external_sort.py +++ b/sorts/external_sort.py @@ -14,7 +14,7 @@ def __init__(self, filename): self.filename = filename self.block_filenames = [] - def write_block(self, data, block_number): + def write_block(self, data, block_number) -> None: filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) @@ -23,7 +23,7 @@ def write_block(self, data, block_number): def get_block_filenames(self): return self.block_filenames - def split(self, block_size, sort_key=None): + def split(self, block_size, sort_key=None) -> None: i = 0 with open(self.filename) as file: while True: @@ -40,7 +40,7 @@ def split(self, block_size, sort_key=None): self.write_block("".join(lines), i) i += 1 - def cleanup(self): + def cleanup(self) -> None: map(os.remove, self.block_filenames) @@ -90,7 +90,7 @@ class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy - def merge(self, filenames, outfilename, buffer_size): + def merge(self, filenames, outfilename, buffer_size) -> None: buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): @@ -110,7 +110,7 @@ class ExternalSort: def __init__(self, block_size): self.block_size = block_size - def sort(self, filename, sort_key=None): + def sort(self, filename, sort_key=None) -> None: num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) @@ -136,7 +136,7 @@ def parse_memory(string): return int(string) -def main(): +def main() -> None: parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" diff --git a/sorts/msd_radix_sort.py b/sorts/msd_radix_sort.py index 6aba4263663a..f6cc5b6d8ce3 100644 --- a/sorts/msd_radix_sort.py +++ b/sorts/msd_radix_sort.py @@ -75,7 +75,7 @@ def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]: return res -def msd_radix_sort_inplace(list_of_ints: list[int]): +def msd_radix_sort_inplace(list_of_ints: list[int]) -> None: """ Inplace implementation of the MSD radix sort algorithm. Sorts based on the binary representation of the integers. diff --git a/sorts/odd_even_transposition_parallel.py b/sorts/odd_even_transposition_parallel.py index 5d4e09b211c0..747899725094 100644 --- a/sorts/odd_even_transposition_parallel.py +++ b/sorts/odd_even_transposition_parallel.py @@ -38,7 +38,7 @@ def oe_process( rr_cv, result_pipe, multiprocessing_context, -): +) -> None: process_lock = multiprocessing_context.Lock() # we perform n swaps since after n swaps we know we are sorted @@ -179,7 +179,7 @@ def odd_even_transposition(arr): # creates a reverse sorted list and sorts it -def main(): +def main() -> None: arr = list(range(10, 0, -1)) print("Initial List") print(*arr) diff --git a/sorts/pigeonhole_sort.py b/sorts/pigeonhole_sort.py index 7fbc6188cfb4..70dc265917c7 100644 --- a/sorts/pigeonhole_sort.py +++ b/sorts/pigeonhole_sort.py @@ -3,7 +3,7 @@ # Algorithm for the pigeonhole sorting -def pigeonhole_sort(a): +def pigeonhole_sort(a) -> None: """ >>> a = [8, 3, 2, 7, 4, 6, 8] >>> b = sorted(a) # a nondestructive sort @@ -39,7 +39,7 @@ def pigeonhole_sort(a): i += 1 -def main(): +def main() -> None: a = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(a) print("Sorted order is:", *a) diff --git a/sorts/recursive_insertion_sort.py b/sorts/recursive_insertion_sort.py index 93465350bee2..b1df234ebef4 100644 --- a/sorts/recursive_insertion_sort.py +++ b/sorts/recursive_insertion_sort.py @@ -5,7 +5,7 @@ from __future__ import annotations -def rec_insertion_sort(collection: list, n: int): +def rec_insertion_sort(collection: list, n: int) -> None: """ Given a collection of numbers and its length, sorts the collections in ascending order @@ -36,7 +36,7 @@ def rec_insertion_sort(collection: list, n: int): rec_insertion_sort(collection, n - 1) -def insert_next(collection: list, index: int): +def insert_next(collection: list, index: int) -> None: """ Inserts the '(index-1)th' element into place diff --git a/sorts/tim_sort.py b/sorts/tim_sort.py index f268fe3ee8bb..692e251bdab7 100644 --- a/sorts/tim_sort.py +++ b/sorts/tim_sort.py @@ -151,7 +151,7 @@ def tim_sort(lst: list[Any] | tuple[Any, ...] | str) -> list[Any]: return sorted_array -def main(): +def main() -> None: lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] sorted_lst = tim_sort(lst) print(sorted_lst) diff --git a/tests/test_sorts.py b/tests/test_sorts.py index adabc2c7d43a..764c3eed2861 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -41,7 +41,7 @@ from sorts.strand_sort import strand_sort -def test_heap_sort(): +def test_heap_sort() -> None: assert heap_sort([]) == [] assert heap_sort([1]) == [1] assert heap_sort([5, 2, 5, 1]) == [1, 2, 5, 5] @@ -103,7 +103,7 @@ class Dog(NamedTuple): @pytest.mark.parametrize("sort", SORTS, ids=lambda f: f.__name__) @pytest.mark.parametrize("case", CASES, ids=repr) -def test_sort_matches_builtin(sort, case): +def test_sort_matches_builtin(sort, case) -> None: """Each sort must reproduce the ordering of the built-in ``sorted``.""" assert list(sort(list(case))) == sorted(case) @@ -124,6 +124,6 @@ def test_sort_matches_builtin(sort, case): ], ids=lambda f: f.__name__, ) -def test_sort_rejects_non_comparable_items(sort): +def test_sort_rejects_non_comparable_items(sort) -> None: with pytest.raises(TypeError): sort([1, "a"]) diff --git a/web_programming/test_fetch_github_info.py b/web_programming/test_fetch_github_info.py index 2e348ee5d913..d7406c45453f 100644 --- a/web_programming/test_fetch_github_info.py +++ b/web_programming/test_fetch_github_info.py @@ -5,7 +5,7 @@ from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info -def test_fetch_github_info(monkeypatch): +def test_fetch_github_info(monkeypatch) -> None: class FakeResponse: def __init__(self, content) -> None: assert isinstance(content, (bytes, str))