diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 89d5a00..6a12d26 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,13 +1,9 @@ # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/python-3/.devcontainer/base.Dockerfile # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster -ARG VARIANT="3.10-bullseye" +ARG VARIANT="3.14-bullseye" FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} -# [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 -ARG NODE_VERSION="none" -RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi - # [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. # COPY requirements.txt /tmp/pip-tmp/ # RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f6ce2d9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +.devcontainer/* -linguist-detectable +.github/** -linguist-detectable \ No newline at end of file diff --git a/.github/workflows/Python.yml b/.github/workflows/Python.yml index 8965866..96bf00e 100644 --- a/.github/workflows/Python.yml +++ b/.github/workflows/Python.yml @@ -26,7 +26,7 @@ jobs: pip install -r requirements.txt - name: Lint run: | - flake8 --max-complexity=10 --max-line-length=120 --statistics + just lint - name: Unit tests run: | - pytest \ No newline at end of file + just test \ No newline at end of file diff --git a/algorithm_theory/binary_search.py b/algorithm_theory/binary_search.py index fff6b21..2961f9f 100644 --- a/algorithm_theory/binary_search.py +++ b/algorithm_theory/binary_search.py @@ -23,7 +23,6 @@ def binary_search_iterative(array: [int], target: int) -> Optional[int]: def binary_search_recursive(array: [int], left: int, right: int, target: int) -> Optional[int]: if right >= left: - mid = int((left + right) / 2) # If element is present at the middle diff --git a/algorithm_theory/jump_search.py b/algorithm_theory/jump_search.py index 5bba190..7ad5f1c 100644 --- a/algorithm_theory/jump_search.py +++ b/algorithm_theory/jump_search.py @@ -5,6 +5,7 @@ import math from typing import Optional + from algorithm_theory.linear_search import linear_search diff --git a/algorithm_theory/linear_search.py b/algorithm_theory/linear_search.py index 7ad2ce6..0466f5d 100644 --- a/algorithm_theory/linear_search.py +++ b/algorithm_theory/linear_search.py @@ -1,6 +1,5 @@ from typing import Optional - # The most basic search. Start from the leftmost element of the array and one by one compare the target with each # element of the array. If the target matches with an element, return the index. diff --git a/arrays/arrays_intersection.py b/arrays/arrays_intersection.py index 65198d7..41379dc 100644 --- a/arrays/arrays_intersection.py +++ b/arrays/arrays_intersection.py @@ -1,8 +1,8 @@ from typing import List - # Leetcode 1213. Intersection of Three Sorted Arrays + def arrays_intersection(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: intersection = set(arr1) intersection = intersection.intersection(arr2) diff --git a/arrays/find_pivot_index.py b/arrays/find_pivot_index.py index bb36a94..f40409d 100644 --- a/arrays/find_pivot_index.py +++ b/arrays/find_pivot_index.py @@ -1,4 +1,3 @@ - def find_pivot_index(nums: [int]) -> int: total = sum(nums) left_sum = 0 diff --git a/arrays/first_not_repeating_character.py b/arrays/first_not_repeating_character.py index 877d76c..4cd52b4 100644 --- a/arrays/first_not_repeating_character.py +++ b/arrays/first_not_repeating_character.py @@ -9,10 +9,10 @@ def first_not_repeating_character(string: str) -> str: length = len(string) index = 0 while index < length: - if string[index] not in string[:index] and string[index] not in string[index + 1:]: + if string[index] not in string[:index] and string[index] not in string[index + 1 :]: return string[index] index += 1 - return '_' + return "_" def first_not_repeating_character_set(string: str) -> str: @@ -21,4 +21,4 @@ def first_not_repeating_character_set(string: str) -> str: if char not in checked_characters and string.index(char) == string.rindex(char): return char checked_characters.add(char) - return '_' + return "_" diff --git a/arrays/largest_number_at_least_twice_of_others.py b/arrays/largest_number_at_least_twice_of_others.py index 37e2b0f..e8c41db 100644 --- a/arrays/largest_number_at_least_twice_of_others.py +++ b/arrays/largest_number_at_least_twice_of_others.py @@ -1,9 +1,12 @@ +from typing import List + + +def largest_number_at_least_twice_of_others(nums: List[int]) -> int: + """Find largest number that is atleast twice the size of any other number -def largest_number_at_least_twice_of_others(nums: [int]) -> int: - """ - Find largest number that is atleast twice the size of any other number :param nums: array of numbers :return: index of number, -1 if none exists + """ largest = None next_largest = None @@ -25,10 +28,11 @@ def largest_number_at_least_twice_of_others(nums: [int]) -> int: def largest_number_at_least_twice_of_others2(nums: [int]) -> int: - """ - Find largest number that is atleast twice the size of any other number + """Find largest number that is atleast twice the size of any other number + :param nums: array of numbers :return: index of number, -1 if none exists + """ if len(nums) == 1: return 0 diff --git a/arrays/merge_sorted_array.py b/arrays/merge_sorted_array.py index 4943cce..7aac3b0 100644 --- a/arrays/merge_sorted_array.py +++ b/arrays/merge_sorted_array.py @@ -1,7 +1,9 @@ from typing import List -def merge_sorted_array(nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int) -> List[int]: +def merge_sorted_array( + nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int +) -> List[int]: index_nums1 = nums1_length - 1 index_nums2 = nums2_length - 1 current_index = nums1_length + nums2_length - 1 diff --git a/arrays/plus_one.py b/arrays/plus_one.py index 93af18a..1c88a62 100644 --- a/arrays/plus_one.py +++ b/arrays/plus_one.py @@ -2,14 +2,13 @@ def plus_one(digits: List[int]) -> List[int]: - """ - Increment array of digits by one as if a number + """Increment array of digits by one as if a number + [1, 2, 3] -> [1, 2, 4] :param digits: list of int numbers representing a non-negative number :return: incremented list """ - for i in reversed(range(len(digits))): digits[i] = (digits[i] + 1) % 10 if digits[i] != 0: diff --git a/arrays/tests/test_first_not_repeating_character.py b/arrays/tests/test_first_not_repeating_character.py index 088ab3d..2c5f0ed 100644 --- a/arrays/tests/test_first_not_repeating_character.py +++ b/arrays/tests/test_first_not_repeating_character.py @@ -1,11 +1,14 @@ -from arrays.first_not_repeating_character import first_not_repeating_character, first_not_repeating_character_set +from arrays.first_not_repeating_character import ( + first_not_repeating_character, + first_not_repeating_character_set, +) def test_first_not_repeating_character(): - assert first_not_repeating_character('aaaaabc') == 'b' - assert first_not_repeating_character('aaaaaa') == '_' + assert first_not_repeating_character("aaaaabc") == "b" + assert first_not_repeating_character("aaaaaa") == "_" def test_first_not_repeating_character_set(): - assert first_not_repeating_character_set('aaaaabc') == 'b' - assert first_not_repeating_character_set('aaaaaa') == '_' + assert first_not_repeating_character_set("aaaaabc") == "b" + assert first_not_repeating_character_set("aaaaaa") == "_" diff --git a/arrays/tests/test_largest_number_twice_of_others.py b/arrays/tests/test_largest_number_twice_of_others.py index af04d7a..06ab085 100644 --- a/arrays/tests/test_largest_number_twice_of_others.py +++ b/arrays/tests/test_largest_number_twice_of_others.py @@ -1,5 +1,7 @@ -from arrays.largest_number_at_least_twice_of_others import largest_number_at_least_twice_of_others, \ - largest_number_at_least_twice_of_others2 +from arrays.largest_number_at_least_twice_of_others import ( + largest_number_at_least_twice_of_others, + largest_number_at_least_twice_of_others2, +) def test_largest_number_at_least_twice_of_others(): diff --git a/arrays/tests/test_max_consecutive_ones.py b/arrays/tests/test_max_consecutive_ones.py index 0d60c36..9f536ee 100644 --- a/arrays/tests/test_max_consecutive_ones.py +++ b/arrays/tests/test_max_consecutive_ones.py @@ -5,4 +5,4 @@ def test_max_consecutive_ones(): assert max_consecutive_ones([1, 1]) == 2 assert max_consecutive_ones([1, 1, 0, 1, 1, 1]) == 3 assert max_consecutive_ones([1, 1, 0, 0, 1, 1]) == 2 - assert max_consecutive_ones([0, 1, 1, 1, 1, 0, 1, 1, 1, 0]) == 4 + assert max_consecutive_ones([0, 1, 1, 1, 1, 0, 1, 1, 1, 0]) == 4 diff --git a/arrays/tests/test_rotate_array.py b/arrays/tests/test_rotate_array.py index 57bf8bb..256337a 100644 --- a/arrays/tests/test_rotate_array.py +++ b/arrays/tests/test_rotate_array.py @@ -1,4 +1,4 @@ -from arrays.rotate_array import rotate_array_with_array, rotate_array_in_place +from arrays.rotate_array import rotate_array_in_place, rotate_array_with_array def test_rotate_array_with_array(): diff --git a/arrays/third_max.py b/arrays/third_max.py index 0722cad..1483dc8 100644 --- a/arrays/third_max.py +++ b/arrays/third_max.py @@ -7,6 +7,6 @@ def third_max(nums: List[int]) -> int: if len(unique_nums) < 3: return max(unique_nums) - unique_nums.remove(max(unique_nums)) # 1st - unique_nums.remove(max(unique_nums)) # 2nd - return max(unique_nums) # 3rd + unique_nums.remove(max(unique_nums)) # 1st + unique_nums.remove(max(unique_nums)) # 2nd + return max(unique_nums) # 3rd diff --git a/binary_tree/binary_tree_path.py b/binary_tree/binary_tree_path.py index c14c1b2..f32a7cc 100644 --- a/binary_tree/binary_tree_path.py +++ b/binary_tree/binary_tree_path.py @@ -30,7 +30,7 @@ def binary_tree_paths(root_node: TreeNode) -> [str]: paths = [] if not root_node: return paths - return get_path(root_node, '', paths) + return get_path(root_node, "", paths) def get_path(node: TreeNode, path: str, paths: [str]) -> [str]: @@ -40,7 +40,7 @@ def get_path(node: TreeNode, path: str, paths: [str]) -> [str]: new_paths.append(path + str(node.val)) return new_paths if node.left: - new_paths += get_path(node.left, path + str(node.val) + '->', paths) + new_paths += get_path(node.left, path + str(node.val) + "->", paths) if node.right: - new_paths += get_path(node.right, path + str(node.val) + '->', paths) + new_paths += get_path(node.right, path + str(node.val) + "->", paths) return new_paths diff --git a/binary_tree/even_odd_tree.py b/binary_tree/even_odd_tree.py index 9f00d72..13fbebc 100644 --- a/binary_tree/even_odd_tree.py +++ b/binary_tree/even_odd_tree.py @@ -1,5 +1,6 @@ from collections import deque from typing import Optional + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/find_mode.py b/binary_tree/find_mode.py index 2d5c999..106aac5 100644 --- a/binary_tree/find_mode.py +++ b/binary_tree/find_mode.py @@ -1,6 +1,6 @@ +from collections import Counter from typing import List -from collections import Counter from binary_tree.tree_node import TreeNode diff --git a/binary_tree/inorder_traversal.py b/binary_tree/inorder_traversal.py index 2efe8fa..93145c5 100644 --- a/binary_tree/inorder_traversal.py +++ b/binary_tree/inorder_traversal.py @@ -1,4 +1,5 @@ from typing import List + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/level_order_traversal.py b/binary_tree/level_order_traversal.py index 8c0edaa..48b2c47 100644 --- a/binary_tree/level_order_traversal.py +++ b/binary_tree/level_order_traversal.py @@ -1,5 +1,6 @@ from collections import deque from typing import List + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/min_depth.py b/binary_tree/min_depth.py index b295b62..4473395 100644 --- a/binary_tree/min_depth.py +++ b/binary_tree/min_depth.py @@ -1,4 +1,5 @@ from collections import deque + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/postorder_traversal.py b/binary_tree/postorder_traversal.py index 229a0ee..68459f7 100644 --- a/binary_tree/postorder_traversal.py +++ b/binary_tree/postorder_traversal.py @@ -1,4 +1,5 @@ from typing import List + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/preorder_traversal.py b/binary_tree/preorder_traversal.py index cb573b5..073d5d8 100644 --- a/binary_tree/preorder_traversal.py +++ b/binary_tree/preorder_traversal.py @@ -1,4 +1,5 @@ from typing import List + from binary_tree.tree_node import TreeNode # class TreeNode: diff --git a/binary_tree/symmetric_binary_tree.py b/binary_tree/symmetric_binary_tree.py index 950f3b2..111c437 100644 --- a/binary_tree/symmetric_binary_tree.py +++ b/binary_tree/symmetric_binary_tree.py @@ -1,4 +1,5 @@ from typing import Optional + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/tests/test_find_mode.py b/binary_tree/tests/test_find_mode.py index 7c5894c..9425c23 100644 --- a/binary_tree/tests/test_find_mode.py +++ b/binary_tree/tests/test_find_mode.py @@ -1,5 +1,5 @@ from binary_tree.find_mode import find_mode -from test_helpers.test_helpers import get_binary_tree, TreeNode +from test_helpers.test_helpers import TreeNode, get_binary_tree def test_find_mode(): diff --git a/binary_tree/tests/test_inorder_traversal.py b/binary_tree/tests/test_inorder_traversal.py index 8b28e85..5b6d566 100644 --- a/binary_tree/tests/test_inorder_traversal.py +++ b/binary_tree/tests/test_inorder_traversal.py @@ -1,5 +1,5 @@ -from test_helpers.test_helpers import get_binary_tree from binary_tree.inorder_traversal import inorder_traversal, inorder_traversal_stack +from test_helpers.test_helpers import get_binary_tree def test_inorder_traversal(): diff --git a/binary_tree/tests/test_level_order_traversal.py b/binary_tree/tests/test_level_order_traversal.py index 874b31b..d36a993 100644 --- a/binary_tree/tests/test_level_order_traversal.py +++ b/binary_tree/tests/test_level_order_traversal.py @@ -1,5 +1,5 @@ -from test_helpers.test_helpers import get_binary_tree from binary_tree.level_order_traversal import level_order_traversal +from test_helpers.test_helpers import get_binary_tree def test_level_order_traversal(): diff --git a/binary_tree/tests/test_next_right_pointer.py b/binary_tree/tests/test_next_right_pointer.py index 5cdc6a3..43c7786 100644 --- a/binary_tree/tests/test_next_right_pointer.py +++ b/binary_tree/tests/test_next_right_pointer.py @@ -1,4 +1,4 @@ -from binary_tree.next_right_pointer import next_right_pointer, Node +from binary_tree.next_right_pointer import Node, next_right_pointer def test_next_right_pointer(): diff --git a/binary_tree/tests/test_postorder_traversal.py b/binary_tree/tests/test_postorder_traversal.py index eb97dae..b8dfab2 100644 --- a/binary_tree/tests/test_postorder_traversal.py +++ b/binary_tree/tests/test_postorder_traversal.py @@ -1,4 +1,7 @@ -from binary_tree.postorder_traversal import postorder_traversal_iterative, postorder_traversal_recursive +from binary_tree.postorder_traversal import ( + postorder_traversal_iterative, + postorder_traversal_recursive, +) from test_helpers.test_helpers import get_binary_tree diff --git a/binary_tree/tests/test_pre_order_traversal.py b/binary_tree/tests/test_pre_order_traversal.py index 484d92d..9298c0d 100644 --- a/binary_tree/tests/test_pre_order_traversal.py +++ b/binary_tree/tests/test_pre_order_traversal.py @@ -1,5 +1,8 @@ -from binary_tree.preorder_traversal import preorder_traversal_iterative, preorder_traversal_morris, \ - preorder_traversal_recursive +from binary_tree.preorder_traversal import ( + preorder_traversal_iterative, + preorder_traversal_morris, + preorder_traversal_recursive, +) from test_helpers.test_helpers import get_binary_tree diff --git a/binary_tree/tests/test_two_sum_iv.py b/binary_tree/tests/test_two_sum_iv.py index 962572c..d16dd55 100644 --- a/binary_tree/tests/test_two_sum_iv.py +++ b/binary_tree/tests/test_two_sum_iv.py @@ -1,5 +1,5 @@ from binary_tree.two_sum_iv import two_sum_iv -from test_helpers.test_helpers import get_binary_tree, TreeNode +from test_helpers.test_helpers import TreeNode, get_binary_tree def test_two_sum_iv(): diff --git a/binary_tree/tree_from_inorder_postorder.py b/binary_tree/tree_from_inorder_postorder.py index d94e39a..0e7a01e 100644 --- a/binary_tree/tree_from_inorder_postorder.py +++ b/binary_tree/tree_from_inorder_postorder.py @@ -1,4 +1,5 @@ from typing import List + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/tree_from_preorder_inorder.py b/binary_tree/tree_from_preorder_inorder.py index 63d9638..e572828 100644 --- a/binary_tree/tree_from_preorder_inorder.py +++ b/binary_tree/tree_from_preorder_inorder.py @@ -1,4 +1,5 @@ from typing import List + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/tree_node.py b/binary_tree/tree_node.py index d6fa2c4..7fd92d0 100644 --- a/binary_tree/tree_node.py +++ b/binary_tree/tree_node.py @@ -1,10 +1,12 @@ from typing import Generic, Optional, TypeVar -T = TypeVar('T') +T = TypeVar("T") class TreeNode(Generic[T]): - def __init__(self, val: T, left: Optional['TreeNode'] = None, right: Optional['TreeNode'] = None): + def __init__( + self, val: T, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None + ): self.val = val self.left: Optional[TreeNode] = left self.right: Optional[TreeNode] = right diff --git a/binary_tree/valid_binary_search_tree.py b/binary_tree/valid_binary_search_tree.py index 301a915..1e6fdb2 100644 --- a/binary_tree/valid_binary_search_tree.py +++ b/binary_tree/valid_binary_search_tree.py @@ -1,7 +1,7 @@ from binary_tree.tree_node import TreeNode -def valid_bst(root: TreeNode, min_value=float('-inf'), max_value=float('inf')) -> bool: +def valid_bst(root: TreeNode, min_value=float("-inf"), max_value=float("inf")) -> bool: if not root: return True diff --git a/circularly_linked_list/insert_cyclic_list.py b/circularly_linked_list/insert_cyclic_list.py index 73d0340..0e895cb 100644 --- a/circularly_linked_list/insert_cyclic_list.py +++ b/circularly_linked_list/insert_cyclic_list.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/data_structures/binary_tree_node.py b/data_structures/binary_tree_node.py index 9c1cccc..caa4853 100644 --- a/data_structures/binary_tree_node.py +++ b/data_structures/binary_tree_node.py @@ -1,5 +1,4 @@ class BinaryTreeNode: - def __init__(self, data, left_node=None, right_node=None): self.__data = data self.__left_node = left_node diff --git a/data_structures/circularly_linked_list.py b/data_structures/circularly_linked_list.py index 9fbff23..0af4e5f 100644 --- a/data_structures/circularly_linked_list.py +++ b/data_structures/circularly_linked_list.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/data_structures/doubly_linked_list.py b/data_structures/doubly_linked_list.py index 6cbbb4a..1fbbb8e 100644 --- a/data_structures/doubly_linked_list.py +++ b/data_structures/doubly_linked_list.py @@ -1,11 +1,11 @@ from typing import Generic, Optional, TypeVar + from data_structures.doubly_linked_list_node import DoublyLinkedListNode -T = TypeVar('T') +T = TypeVar("T") class DoublyLinkedList(Generic[T]): - def __init__(self): self.__head: DoublyLinkedListNode = DoublyLinkedListNode() self.__tail: DoublyLinkedListNode = DoublyLinkedListNode() diff --git a/data_structures/doubly_linked_list_node.py b/data_structures/doubly_linked_list_node.py index b314962..e92a781 100644 --- a/data_structures/doubly_linked_list_node.py +++ b/data_structures/doubly_linked_list_node.py @@ -1,13 +1,15 @@ from typing import Generic, Optional, TypeVar - -T = TypeVar('T') +T = TypeVar("T") class DoublyLinkedListNode(Generic[T]): - def __init__(self, data: T = None, - previous_node: Optional['DoublyLinkedListNode'] = None, - next_node: Optional['DoublyLinkedListNode'] = None): + def __init__( + self, + data: T = None, + previous_node: Optional["DoublyLinkedListNode"] = None, + next_node: Optional["DoublyLinkedListNode"] = None, + ): self.data: T = data self.previous: Optional[DoublyLinkedListNode] = previous_node self.next: Optional[DoublyLinkedListNode] = next_node diff --git a/data_structures/min_heap.py b/data_structures/min_heap.py new file mode 100644 index 0000000..1c72204 --- /dev/null +++ b/data_structures/min_heap.py @@ -0,0 +1,37 @@ +class MinHeap: + def __init__(self): + self.list = [] + + def insert(self, val): + self.list.append(val) + self._sift_up(len(self.list) - 1) + + def is_empty(self): + return len(self.list) == 0 + + def size(self): + return len(self.list) + + def values(self): + values = [] + for value in self.list: + values.append(value) + return values + + def _get_parent(self, idx): + return (idx - 1) // 2 + + def _sift_up(self, idx): + current_index = idx + + while current_index > 0: + parent = self._get_parent(current_index) + + if self.list[current_index] < self.list[parent]: + self.list[current_index], self.list[parent] = ( + self.list[parent], + self.list[current_index], + ) + current_index = parent + else: + break diff --git a/data_structures/queues.py b/data_structures/queues.py index 48ca1c2..e931a79 100644 --- a/data_structures/queues.py +++ b/data_structures/queues.py @@ -1,13 +1,14 @@ -from typing import Generic, TypeVar, List +from typing import Generic, List, TypeVar + from data_structures.doubly_linked_list import DoublyLinkedList -T = TypeVar('T') +T = TypeVar("T") class QueueList(Generic[T]): - """ - Basic queue backed with a list. Not optimal since list has O(N) complexity for - inserting and removing elements at the beginning + """Basic queue backed with a list. + + Not optimal since list has O(N) complexity for inserting and removing elements at the beginning """ def __init__(self): @@ -24,9 +25,7 @@ def enqueue(self, element: T): class QueueLinkedList(Generic[T]): - """ - Queue backed by a doubly linked list - """ + """Queue backed by a doubly linked list""" def __init__(self): self.linked_list = DoublyLinkedList() @@ -44,7 +43,6 @@ def enqueue(self, element: T): class CircularQueue(Generic[T]): - def __init__(self, k: int): self.queue = [0] * k self.count = 0 @@ -67,17 +65,13 @@ def dequeue(self) -> bool: return True def front(self) -> T: - """ - Get the front item from the queue. - """ + """Get the front item from the queue.""" if self.isempty(): return -1 return self.queue[self.head] def rear(self) -> T: - """ - Get the last item from the queue. - """ + """Get the last item from the queue.""" if self.isempty(): return -1 tail = (self.head + self.count - 1) % self.size diff --git a/data_structures/singly_linked_list.py b/data_structures/singly_linked_list.py index 1f62762..e3a6f41 100644 --- a/data_structures/singly_linked_list.py +++ b/data_structures/singly_linked_list.py @@ -2,11 +2,10 @@ from data_structures.singly_linked_list_node import SinglyLinkedListNode -T = TypeVar('T') +T = TypeVar("T") class SinglyLinkedList(Generic[T]): - def __init__(self): self.__head: SinglyLinkedListNode = SinglyLinkedListNode() @@ -58,7 +57,7 @@ def insert(self, data: T, index: int) -> None: current_node = current_node.next count += 1 if count < index: - IndexError('Index out of bounds') + IndexError("Index out of bounds") def remove(self, index: int) -> None: count = 0 diff --git a/data_structures/singly_linked_list_node.py b/data_structures/singly_linked_list_node.py index d76345f..3b49579 100644 --- a/data_structures/singly_linked_list_node.py +++ b/data_structures/singly_linked_list_node.py @@ -1,10 +1,9 @@ from typing import Generic, Optional, TypeVar - -T = TypeVar('T') +T = TypeVar("T") class SinglyLinkedListNode(Generic[T]): - def __init__(self, data: T = None, next_node: Optional['SinglyLinkedListNode'] = None): + def __init__(self, data: T = None, next_node: Optional["SinglyLinkedListNode"] = None): self.data = data self.next = next_node diff --git a/data_structures/stack.py b/data_structures/stack.py index f8d0213..f6aa2de 100644 --- a/data_structures/stack.py +++ b/data_structures/stack.py @@ -1,12 +1,11 @@ from typing import Generic, TypeVar -T = TypeVar('T') +T = TypeVar("T") class StackList(Generic[T]): - """ - Stack backed by List. List is O(1) for append and pop - """ + """Stack backed by List. List is O(1) for append and pop""" + def __init__(self): self.__list = [] diff --git a/data_structures/tests/test_queue.py b/data_structures/tests/test_queue.py index 064b6f4..8326b6b 100644 --- a/data_structures/tests/test_queue.py +++ b/data_structures/tests/test_queue.py @@ -1,4 +1,4 @@ -from data_structures.queues import CircularQueue, QueueList, QueueLinkedList +from data_structures.queues import CircularQueue, QueueLinkedList, QueueList def test_queue_list(): diff --git a/data_structures/tests/test_trie_with_array.py b/data_structures/tests/test_trie_with_array.py index ccb4129..5e8b30f 100644 --- a/data_structures/tests/test_trie_with_array.py +++ b/data_structures/tests/test_trie_with_array.py @@ -3,7 +3,7 @@ def test_trie_with_array(): trie = TrieWithArray() - assert trie.insert('ab') is None - assert not trie.search('a') - assert trie.search('ab') - assert trie.starts_with('a') + assert trie.insert("ab") is None + assert not trie.search("a") + assert trie.search("ab") + assert trie.starts_with("a") diff --git a/data_structures/tests/test_trie_with_dictionary.py b/data_structures/tests/test_trie_with_dictionary.py index b99678f..c59bb00 100644 --- a/data_structures/tests/test_trie_with_dictionary.py +++ b/data_structures/tests/test_trie_with_dictionary.py @@ -3,7 +3,7 @@ def test_trie_with_dictionary(): trie = TrieWithDictionary() - assert trie.insert('ab') is None - assert not trie.search('a') - assert trie.search('ab') - assert trie.starts_with('a') + assert trie.insert("ab") is None + assert not trie.search("a") + assert trie.search("ab") + assert trie.starts_with("a") diff --git a/data_structures/tests/test_trie_with_flat_dictionary.py b/data_structures/tests/test_trie_with_flat_dictionary.py index c1553b1..b245dbd 100644 --- a/data_structures/tests/test_trie_with_flat_dictionary.py +++ b/data_structures/tests/test_trie_with_flat_dictionary.py @@ -3,7 +3,7 @@ def test_trie_with_flat_dictionary(): trie = TrieWithFlatDictionary() - assert trie.insert('ab') is None - assert not trie.search('a') - assert trie.search('ab') - assert trie.starts_with('a') + assert trie.insert("ab") is None + assert not trie.search("a") + assert trie.search("ab") + assert trie.starts_with("a") diff --git a/data_structures/trie_with_array.py b/data_structures/trie_with_array.py index 60517c6..afb235f 100644 --- a/data_structures/trie_with_array.py +++ b/data_structures/trie_with_array.py @@ -6,12 +6,10 @@ def __init__(self): self.head: TrieNode = TrieNode() def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ + """Inserts a word into the trie.""" current_trie = self.head for index in range(1, len(word) + 1): - node_index = ord(word[:index][-1]) - ord('a') + node_index = ord(word[:index][-1]) - ord("a") if current_trie.child_nodes[node_index]: current_trie = current_trie.child_nodes[node_index] else: @@ -19,12 +17,10 @@ def insert(self, word: str) -> None: current_trie = current_trie.child_nodes[node_index] def search(self, word: str) -> bool: - """ - Returns True if the word is in the trie. - """ + """Returns True if the word is in the trie.""" current_trie = self.head for index in range(1, len(word) + 1): - node_index = ord(word[:index][-1]) - ord('a') + node_index = ord(word[:index][-1]) - ord("a") if current_trie.child_nodes[node_index]: current_trie = current_trie.child_nodes[node_index] else: @@ -32,12 +28,10 @@ def search(self, word: str) -> bool: return current_trie.child_nodes == [None] * 26 def starts_with(self, prefix: str) -> bool: - """ - Returns True if there is any word in the trie that starts with the given prefix. - """ + """Returns True if there is any word in the trie that starts with the given prefix.""" current_trie = self.head for index in range(1, len(prefix) + 1): - node_index = ord(prefix[:index][-1]) - ord('a') + node_index = ord(prefix[:index][-1]) - ord("a") if current_trie.child_nodes[node_index]: current_trie = current_trie.child_nodes[node_index] else: diff --git a/data_structures/trie_with_dictionary.py b/data_structures/trie_with_dictionary.py index 7365ed2..652a5bb 100644 --- a/data_structures/trie_with_dictionary.py +++ b/data_structures/trie_with_dictionary.py @@ -3,15 +3,11 @@ class TrieWithDictionary: def __init__(self): - """ - Initialize your data structure here. - """ + """Initialize your data structure here.""" self.head: TrieNode = TrieNode() def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ + """Inserts a word into the trie.""" current_trie = self.head for index in range(1, len(word) + 1): if word[:index] in current_trie.child_nodes: @@ -22,9 +18,7 @@ def insert(self, word: str) -> None: current_trie = child_node def search(self, word: str) -> bool: - """ - Returns if the word is in the trie. - """ + """Returns if the word is in the trie.""" current_trie = self.head for index in range(1, len(word) + 1): if word[:index] in current_trie.child_nodes: @@ -34,9 +28,7 @@ def search(self, word: str) -> bool: return len(current_trie.child_nodes) == 0 def starts_with(self, prefix: str) -> bool: - """ - Returns if there is any word in the trie that starts with the given prefix. - """ + """Returns if there is any word in the trie that starts with the given prefix.""" current_trie = self.head for index in range(1, len(prefix) + 1): if prefix[:index] in current_trie.child_nodes: @@ -48,4 +40,4 @@ def starts_with(self, prefix: str) -> bool: class TrieNode: def __init__(self): - self.child_nodes: Dict[str: TrieNode] = dict() + self.child_nodes: Dict[str:TrieNode] = dict() diff --git a/data_structures/trie_with_flat_dictionary.py b/data_structures/trie_with_flat_dictionary.py index 48e7507..560a74a 100644 --- a/data_structures/trie_with_flat_dictionary.py +++ b/data_structures/trie_with_flat_dictionary.py @@ -2,34 +2,26 @@ class TrieWithFlatDictionary: - """ - O(1) for accessing elements + """O(1) for accessing elements + O(M * N) - Because multiple values of a key must be tracked (plus their associated True/False values) """ def __init__(self): - """ - Initialize your data structure here. - """ - self.nodes: Dict[str: bool] = dict() + """Initialize your data structure here.""" + self.nodes: Dict[str:bool] = dict() def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ + """Inserts a word into the trie.""" for index in range(1, len(word)): if self.nodes.get(word[:index]) is None: self.nodes[word[:index]] = False self.nodes[word] = True def search(self, word: str) -> bool: - """ - Returns if the word is in the trie. - """ + """Returns if the word is in the trie.""" return self.nodes.get(word) is True def starts_with(self, prefix: str) -> bool: - """ - Returns if there is any word in the trie that starts with the given prefix. - """ + """Return if word in the trie that starts with the given prefix.""" return self.nodes.get(prefix) is not None diff --git a/doubly_linked_list/flatten_doubly_linked_lists.py b/doubly_linked_list/flatten_doubly_linked_lists.py index 9a126bf..f67fd6e 100644 --- a/doubly_linked_list/flatten_doubly_linked_lists.py +++ b/doubly_linked_list/flatten_doubly_linked_lists.py @@ -2,15 +2,17 @@ class Node: - def __init__(self, - val: int, - previous_node: Optional['Node'], - next_node: Optional['Node'], - child_node: Optional['Node']): + def __init__( + self, + val: int, + previous_node: Optional["Node"], + next_node: Optional["Node"], + child_node: Optional["Node"], + ): self.data: int = val - self.previous: Optional['Node'] = previous_node - self.next: Optional['Node'] = next_node - self.child: Optional['Node'] = child_node + self.previous: Optional["Node"] = previous_node + self.next: Optional["Node"] = next_node + self.child: Optional["Node"] = child_node def flatten(head: Node) -> Node: diff --git a/doubly_linked_list/tests/test_flatten_doubly_linked_lists.py b/doubly_linked_list/tests/test_flatten_doubly_linked_lists.py index e35a8b0..426cd7a 100644 --- a/doubly_linked_list/tests/test_flatten_doubly_linked_lists.py +++ b/doubly_linked_list/tests/test_flatten_doubly_linked_lists.py @@ -1,5 +1,4 @@ -from doubly_linked_list.flatten_doubly_linked_lists import flatten, flatten_iterative -from doubly_linked_list.flatten_doubly_linked_lists import Node +from doubly_linked_list.flatten_doubly_linked_lists import Node, flatten, flatten_iterative from test_helpers.test_helpers import get_list_values diff --git a/integers/fibonacci.py b/integers/fibonacci.py index d116216..789de24 100644 --- a/integers/fibonacci.py +++ b/integers/fibonacci.py @@ -3,16 +3,16 @@ def fibonacci(number: int, memo: Dict[int, int] = None) -> int: - """ - Generate the fibonacci number for n + """Generate the fibonacci number for n + Uses a dictionary to store previously computed values 0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc :param number: iteration of the Fibonacci sequence :param memo: memoization store, will be cached since it is mutable :return: Fibonacci number - """ + """ if not memo: memo = {0: 0, 1: 1} @@ -24,13 +24,14 @@ def fibonacci(number: int, memo: Dict[int, int] = None) -> int: @lru_cache(maxsize=None) def fibonacci2(number: int) -> int: - """ - Generate the fibonacci number for n + """Generate the fibonacci number for n + Utilizes caching to mimic literal memoization, has lower recursive limit... 0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc :param number: iteration of the Fibonacci sequence :return: Fibonacci number + """ if number < 2: return number @@ -38,15 +39,15 @@ def fibonacci2(number: int) -> int: def fibonacci3(number: int) -> int: - """ - Generate the fibonacci number for n + """Generate the fibonacci number for n + iterative approach, no recursion constraints 0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc :param number: iteration of the Fibonacci sequence :return: Fibonacci number - """ + """ if number == 0: return 0 last_nbr: int = 0 @@ -71,15 +72,14 @@ def fibonacci_with_array(number: int, memo=None) -> int: def fibonacci_sequence(number: int) -> Generator[int, None, None]: - """ - Generate the fibonacci number for n + """Generate the fibonacci number for n + Utilizes a generator 0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc :param number: iteration of the Fibonacci sequence :return: Fibonacci number Generator """ - yield 0 if number > 0: yield 1 diff --git a/integers/reverse_number.py b/integers/reverse_number.py index c46e55e..b0b4b65 100644 --- a/integers/reverse_number.py +++ b/integers/reverse_number.py @@ -9,7 +9,7 @@ def reverse_number(number: int) -> int: reversed_number = int(str(abs(number))[::-1]) - if reversed_number > 2 ** 31 - 1: # Check for integer overflow (per question) + if reversed_number > 2**31 - 1: # Check for integer overflow (per question) return 0 if number < 0: diff --git a/integers/tests/test_fibonacci.py b/integers/tests/test_fibonacci.py index bbc8b9b..0bc7696 100644 --- a/integers/tests/test_fibonacci.py +++ b/integers/tests/test_fibonacci.py @@ -1,4 +1,10 @@ -from integers.fibonacci import fibonacci, fibonacci2, fibonacci3, fibonacci_sequence, fibonacci_with_array +from integers.fibonacci import ( + fibonacci, + fibonacci2, + fibonacci3, + fibonacci_sequence, + fibonacci_with_array, +) def test_fibonacci(): diff --git a/justfile b/justfile new file mode 100644 index 0000000..f976328 --- /dev/null +++ b/justfile @@ -0,0 +1,4 @@ +lint: + ruff check . --fix && ruff format . +test: + pytest \ No newline at end of file diff --git a/math_problems/count_primes.py b/math_problems/count_primes.py index f1999e4..3254db3 100644 --- a/math_problems/count_primes.py +++ b/math_problems/count_primes.py @@ -1,5 +1,3 @@ - - def count_primes(number: int) -> int: is_prime = [True] * number diff --git a/math_problems/fizz_buzz.py b/math_problems/fizz_buzz.py index 386ec65..bde9b2c 100644 --- a/math_problems/fizz_buzz.py +++ b/math_problems/fizz_buzz.py @@ -11,12 +11,12 @@ def fizz_buzz(iterations: int) -> List[str]: three = num % 3 == 0 five = num % 5 == 0 if three and five: - output.append('FizzBuzz') + output.append("FizzBuzz") elif three: - output.append('Fizz') + output.append("Fizz") elif five: - output.append('Buzz') + output.append("Buzz") else: - output.append(f'{num}') + output.append(f"{num}") return output diff --git a/math_problems/leap_year.py b/math_problems/leap_year.py index 6e2412c..d652003 100644 --- a/math_problems/leap_year.py +++ b/math_problems/leap_year.py @@ -1,8 +1,5 @@ - - def leap_year(year: int) -> bool: - """ - In the Gregorian calendar, three conditions are used to identify leap years: + """In the Gregorian calendar, three conditions are used to identify leap years: The year can be evenly divided by 4, is a leap year, unless: The year can be evenly divided by 100, it is NOT a leap year, unless: diff --git a/math_problems/tests/test_fizz_buzz.py b/math_problems/tests/test_fizz_buzz.py index 650cd55..17409fe 100644 --- a/math_problems/tests/test_fizz_buzz.py +++ b/math_problems/tests/test_fizz_buzz.py @@ -2,7 +2,22 @@ def test_fizz_buzz(): - assert fizz_buzz(3) == ['1', '2', 'Fizz'] - assert fizz_buzz(5) == ['1', '2', 'Fizz', '4', 'Buzz'] - assert fizz_buzz(15) == ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', - 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz'] + assert fizz_buzz(3) == ["1", "2", "Fizz"] + assert fizz_buzz(5) == ["1", "2", "Fizz", "4", "Buzz"] + assert fizz_buzz(15) == [ + "1", + "2", + "Fizz", + "4", + "Buzz", + "Fizz", + "7", + "8", + "Fizz", + "Buzz", + "11", + "Fizz", + "13", + "14", + "FizzBuzz", + ] diff --git a/multi_dimensional_arrays/diagonal_traverse.py b/multi_dimensional_arrays/diagonal_traverse.py index 268dd38..e361007 100644 --- a/multi_dimensional_arrays/diagonal_traverse.py +++ b/multi_dimensional_arrays/diagonal_traverse.py @@ -2,8 +2,7 @@ def diagonal_traverse(matrix: List[List[int]]) -> List[int]: - """ - Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order. + """Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order. Input: [[1, 2, 3], diff --git a/multi_dimensional_arrays/rotate_image.py b/multi_dimensional_arrays/rotate_image.py index fbba0ed..8c91b0f 100644 --- a/multi_dimensional_arrays/rotate_image.py +++ b/multi_dimensional_arrays/rotate_image.py @@ -1,5 +1,3 @@ - - def rotate_image_90_degrees(matrix: [[int]]) -> [[int]]: size = len(matrix) layer_count = int(size / 2) diff --git a/multi_dimensional_arrays/tests/test_diagonal_traverse.py b/multi_dimensional_arrays/tests/test_diagonal_traverse.py index fe4e036..1db4c1f 100644 --- a/multi_dimensional_arrays/tests/test_diagonal_traverse.py +++ b/multi_dimensional_arrays/tests/test_diagonal_traverse.py @@ -2,10 +2,6 @@ def test_diagonal_traverse(): - arr = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] - ] + arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert diagonal_traverse(arr) == [1, 2, 4, 7, 5, 3, 6, 8, 9] assert diagonal_traverse([]) == [] diff --git a/multi_dimensional_arrays/tests/test_rotate_image.py b/multi_dimensional_arrays/tests/test_rotate_image.py index a5f4ec4..0aaffe6 100644 --- a/multi_dimensional_arrays/tests/test_rotate_image.py +++ b/multi_dimensional_arrays/tests/test_rotate_image.py @@ -2,12 +2,8 @@ def test_rotate_image_90_degrees(): - arr_a = [[1, 2, 3], - [4, 5, 6], - [7, 8, 9]] + arr_a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] - arr_b = [[7, 4, 1], - [8, 5, 2], - [9, 6, 3]] + arr_b = [[7, 4, 1], [8, 5, 2], [9, 6, 3]] assert rotate_image_90_degrees(arr_a) == arr_b diff --git a/multi_dimensional_arrays/tests/test_spiral_matrix.py b/multi_dimensional_arrays/tests/test_spiral_matrix.py index 4071d03..206f867 100644 --- a/multi_dimensional_arrays/tests/test_spiral_matrix.py +++ b/multi_dimensional_arrays/tests/test_spiral_matrix.py @@ -11,16 +11,8 @@ def test_spiral_matrix(): matrix = [[6, 9, 7]] assert spiral_matrix(matrix) == [6, 9, 7] - matrix = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] - ] + matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert spiral_matrix(matrix) == [1, 2, 3, 6, 9, 8, 7, 4, 5] - matrix = [ - [1, 2, 3, 4], - [5, 6, 7, 8], - [9, 10, 11, 12] - ] + matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] assert spiral_matrix(matrix) == [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] diff --git a/n_ary_tree/encode_decode_tree.py b/n_ary_tree/encode_decode_tree.py index 9f27602..f7872d7 100644 --- a/n_ary_tree/encode_decode_tree.py +++ b/n_ary_tree/encode_decode_tree.py @@ -1,5 +1,6 @@ from collections import deque from typing import Optional + from binary_tree.tree_node import TreeNode from n_ary_tree.nary_tree_node import NaryTreeNode diff --git a/n_ary_tree/level_order_traversal.py b/n_ary_tree/level_order_traversal.py index 64281dc..9f11efd 100644 --- a/n_ary_tree/level_order_traversal.py +++ b/n_ary_tree/level_order_traversal.py @@ -1,4 +1,5 @@ from typing import List + from n_ary_tree.nary_tree_node import NaryTreeNode diff --git a/n_ary_tree/nary_tree_node.py b/n_ary_tree/nary_tree_node.py index 82b0c86..105da9c 100644 --- a/n_ary_tree/nary_tree_node.py +++ b/n_ary_tree/nary_tree_node.py @@ -1,9 +1,9 @@ from typing import List, Optional, TypeVar -T = TypeVar('T') +T = TypeVar("T") class NaryTreeNode: - def __init__(self, value: T, children: Optional[List['NaryTreeNode']] = None): + def __init__(self, value: T, children: Optional[List["NaryTreeNode"]] = None): self.value: T = value self.children: Optional[List[NaryTreeNode]] = children diff --git a/n_ary_tree/postorder_traversal.py b/n_ary_tree/postorder_traversal.py index 0bab6d9..91f630c 100644 --- a/n_ary_tree/postorder_traversal.py +++ b/n_ary_tree/postorder_traversal.py @@ -1,4 +1,5 @@ from typing import List, Optional + from n_ary_tree.nary_tree_node import NaryTreeNode diff --git a/n_ary_tree/postorder_traversal_iterative.py b/n_ary_tree/postorder_traversal_iterative.py index 45e3678..e83349a 100644 --- a/n_ary_tree/postorder_traversal_iterative.py +++ b/n_ary_tree/postorder_traversal_iterative.py @@ -1,5 +1,6 @@ from collections import deque from typing import List, Optional + from n_ary_tree.nary_tree_node import NaryTreeNode diff --git a/n_ary_tree/preorder_traversal.py b/n_ary_tree/preorder_traversal.py index 4462993..59db7f4 100644 --- a/n_ary_tree/preorder_traversal.py +++ b/n_ary_tree/preorder_traversal.py @@ -1,4 +1,5 @@ from typing import List + from n_ary_tree import nary_tree_node diff --git a/n_ary_tree/preorder_traversal_iterative.py b/n_ary_tree/preorder_traversal_iterative.py index 26634e1..0106182 100644 --- a/n_ary_tree/preorder_traversal_iterative.py +++ b/n_ary_tree/preorder_traversal_iterative.py @@ -1,4 +1,5 @@ from typing import List + from n_ary_tree.nary_tree_node import NaryTreeNode diff --git a/n_ary_tree/tests/test_encode_decode_tree.py b/n_ary_tree/tests/test_encode_decode_tree.py index ae7f0b9..e096c0b 100644 --- a/n_ary_tree/tests/test_encode_decode_tree.py +++ b/n_ary_tree/tests/test_encode_decode_tree.py @@ -1,5 +1,5 @@ from n_ary_tree.encode_decode_tree import decode, encode -from test_helpers.test_helpers import get_n_nary_tree, get_n_ary_tree_values +from test_helpers.test_helpers import get_n_ary_tree_values, get_n_nary_tree def test_encode_decode(): diff --git a/n_ary_tree/tests/test_level_order_traversal.py b/n_ary_tree/tests/test_level_order_traversal.py index fc9258a..c1f73d7 100644 --- a/n_ary_tree/tests/test_level_order_traversal.py +++ b/n_ary_tree/tests/test_level_order_traversal.py @@ -3,4 +3,9 @@ def test_level_order_traversal(): - assert level_order_traversal(get_n_nary_tree()) == [[1], [2, 3, 4], [5, 6, 8, 9, 10, 11], [7, 12]] + assert level_order_traversal(get_n_nary_tree()) == [ + [1], + [2, 3, 4], + [5, 6, 8, 9, 10, 11], + [7, 12], + ] diff --git a/n_ary_tree/tests/test_postorder_traversal_iterative.py b/n_ary_tree/tests/test_postorder_traversal_iterative.py index 465c131..ea6ca3f 100644 --- a/n_ary_tree/tests/test_postorder_traversal_iterative.py +++ b/n_ary_tree/tests/test_postorder_traversal_iterative.py @@ -1,7 +1,20 @@ -from test_helpers.test_helpers import get_n_nary_tree from n_ary_tree.postorder_traversal_iterative import postorder_traversal_iterative +from test_helpers.test_helpers import get_n_nary_tree def test_postorder_traversal_iterative(): - assert postorder_traversal_iterative(get_n_nary_tree()) == [7, 5, 6, 2, 8, 3, 9, 10, 12, 11, 4, 1] + assert postorder_traversal_iterative(get_n_nary_tree()) == [ + 7, + 5, + 6, + 2, + 8, + 3, + 9, + 10, + 12, + 11, + 4, + 1, + ] assert postorder_traversal_iterative(None) == [] diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..e9a46d7 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,14 @@ +[tool.ruff] +line-length = 100 +target-version = "py312" + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "N", "D"] # Choose your rule categories +ignore = ["D100", "D101", "D102", "D103", "D104", "D105", "D107", "D211", "D203", "D213", "D400", "D401", "D415"] +extend-ignore = ["E501"] # Line too long (handled by formatter) + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["D"] # Ignore docstring (D) errors in tests + +[tool.ruff.format] +quote-style = "double" \ No newline at end of file diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..03f586d --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +pythonpath = . \ No newline at end of file diff --git a/queues/moving_average.py b/queues/moving_average.py index 89f661b..bfec618 100644 --- a/queues/moving_average.py +++ b/queues/moving_average.py @@ -2,7 +2,6 @@ class MovingAverage: - def __init__(self, max_size: int): self.max_size = max_size self.queue = deque() diff --git a/queues/queue_with_stack.py b/queues/queue_with_stack.py index 2e8dd3c..1edd8c0 100644 --- a/queues/queue_with_stack.py +++ b/queues/queue_with_stack.py @@ -1,7 +1,7 @@ -from typing import Deque, Generic, TypeVar from collections import deque +from typing import Deque, Generic, TypeVar -T = TypeVar('T') +T = TypeVar("T") class Queue(Generic[T]): diff --git a/queues/tests/test_walls_and_gates.py b/queues/tests/test_walls_and_gates.py index 0d09874..e95c0f0 100644 --- a/queues/tests/test_walls_and_gates.py +++ b/queues/tests/test_walls_and_gates.py @@ -6,7 +6,7 @@ def test_walls_and_gates(): [2147483647, -1, 0, 2147483647], [2147483647, 2147483647, 2147483647, -1], [2147483647, -1, 2147483647, -1], - [0, -1, 2147483647, 2147483647] + [0, -1, 2147483647, 2147483647], ] assert walls_and_gates(rooms) == [[3, -1, 0, 1], [2, 2, 1, -1], [1, -1, 2, -1], [0, -1, 3, 4]] diff --git a/requirements.txt b/requirements.txt index 4f84dd0..165e21c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,18 +1,3 @@ -attrs==21.4.0 -build==1.4.0 -click==8.3.1 -flake8==7.3.0 -iniconfig==1.1.1 -mccabe==0.7.0 -packaging==26.0 -pluggy==1.6.0 -py==1.11.0 -pycodestyle==2.14.0 -pyflakes==3.4.0 -Pygments==2.20.0 -pyparsing==3.0.9 -pyproject_hooks==1.2.0 pytest==9.0.3 -setuptools==83.0.0 -tomli==2.0.1 -wheel==0.46.3 +ruff==0.15.9 +rust-just==1.48.1 diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 8a688d2..0000000 --- a/setup.cfg +++ /dev/null @@ -1,3 +0,0 @@ -[flake8] - -exclude = .git,__pycache__,.venv \ No newline at end of file diff --git a/singly_linked_lists/add_two_numbers.py b/singly_linked_lists/add_two_numbers.py index a8f17a5..937e64a 100644 --- a/singly_linked_lists/add_two_numbers.py +++ b/singly_linked_lists/add_two_numbers.py @@ -1,9 +1,11 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def add_two_numbers(head1: Optional[SinglyLinkedListNode], - head2: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: +def add_two_numbers( + head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] +) -> Optional[SinglyLinkedListNode]: node1 = head1 node2 = head2 dummy_node = SinglyLinkedListNode(0) diff --git a/singly_linked_lists/copy_list_with_random_pointer.py b/singly_linked_lists/copy_list_with_random_pointer.py index 10f9e47..a8230c7 100644 --- a/singly_linked_lists/copy_list_with_random_pointer.py +++ b/singly_linked_lists/copy_list_with_random_pointer.py @@ -2,7 +2,7 @@ class Node: - def __init__(self, value: int, next_node: 'Node' = None, random: 'Node' = None): + def __init__(self, value: int, next_node: "Node" = None, random: "Node" = None): self.value = value self.next = next_node self.random = random diff --git a/singly_linked_lists/delete_duplicates.py b/singly_linked_lists/delete_duplicates.py index 147cec2..5fccb45 100644 --- a/singly_linked_lists/delete_duplicates.py +++ b/singly_linked_lists/delete_duplicates.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/detect_cycle.py b/singly_linked_lists/detect_cycle.py index 4d3d553..daf9eb3 100644 --- a/singly_linked_lists/detect_cycle.py +++ b/singly_linked_lists/detect_cycle.py @@ -1,4 +1,5 @@ from typing import Optional, Set + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/find_middle_node.py b/singly_linked_lists/find_middle_node.py index 75c025d..d1ec7e3 100644 --- a/singly_linked_lists/find_middle_node.py +++ b/singly_linked_lists/find_middle_node.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/intersection_two_linked_lists.py b/singly_linked_lists/intersection_two_linked_lists.py index 5f610cf..dab352e 100644 --- a/singly_linked_lists/intersection_two_linked_lists.py +++ b/singly_linked_lists/intersection_two_linked_lists.py @@ -1,8 +1,11 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def get_intersection_node(head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: +def get_intersection_node( + head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode +) -> Optional[SinglyLinkedListNode]: if not head_a or not head_b: return None diff --git a/singly_linked_lists/intersection_two_linked_lists_with_set.py b/singly_linked_lists/intersection_two_linked_lists_with_set.py index 62ec481..b95d93d 100644 --- a/singly_linked_lists/intersection_two_linked_lists_with_set.py +++ b/singly_linked_lists/intersection_two_linked_lists_with_set.py @@ -1,9 +1,11 @@ from typing import Optional, Set + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def get_intersection_node_with_set(head_a: SinglyLinkedListNode, - head_b: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: +def get_intersection_node_with_set( + head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode +) -> Optional[SinglyLinkedListNode]: nodes: Set[SinglyLinkedListNode] = set() node_a: SinglyLinkedListNode = head_a node_b: SinglyLinkedListNode = head_b diff --git a/singly_linked_lists/linked_list_cycle.py b/singly_linked_lists/linked_list_cycle.py index 5cf1f43..160a210 100644 --- a/singly_linked_lists/linked_list_cycle.py +++ b/singly_linked_lists/linked_list_cycle.py @@ -1,7 +1,8 @@ from typing import Optional, Set, TypeVar + from data_structures.singly_linked_list_node import SinglyLinkedListNode -T = TypeVar('T') +T = TypeVar("T") # Time: O(N + K) -> O(N), Space: O(1) diff --git a/singly_linked_lists/merge_k_lists.py b/singly_linked_lists/merge_k_lists.py index 5e9aef9..a002fbe 100644 --- a/singly_linked_lists/merge_k_lists.py +++ b/singly_linked_lists/merge_k_lists.py @@ -1,4 +1,5 @@ from typing import List, Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -10,7 +11,7 @@ def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[Singl while lists: min_node = None - smallest = float('inf') + smallest = float("inf") for index, head in enumerate(lists): if head and head.data <= smallest: diff --git a/singly_linked_lists/merge_two_sorted_lists.py b/singly_linked_lists/merge_two_sorted_lists.py index 11093cb..e72a4b7 100644 --- a/singly_linked_lists/merge_two_sorted_lists.py +++ b/singly_linked_lists/merge_two_sorted_lists.py @@ -1,9 +1,11 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def merge_two_lists(head1: Optional[SinglyLinkedListNode], - head2: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: +def merge_two_lists( + head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] +) -> Optional[SinglyLinkedListNode]: if not head1 and not head2: return None diff --git a/singly_linked_lists/odd_even_linked_list.py b/singly_linked_lists/odd_even_linked_list.py index 0a80b7f..0cff15e 100644 --- a/singly_linked_lists/odd_even_linked_list.py +++ b/singly_linked_lists/odd_even_linked_list.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/palindrome_linked_list.py b/singly_linked_lists/palindrome_linked_list.py index 4a7d64b..132d04e 100644 --- a/singly_linked_lists/palindrome_linked_list.py +++ b/singly_linked_lists/palindrome_linked_list.py @@ -1,7 +1,8 @@ from typing import Optional + +from data_structures.singly_linked_list_node import SinglyLinkedListNode from singly_linked_lists.find_middle_node import find_middle_node from singly_linked_lists.reverse_linked_list import reverse_linked_list -from data_structures.singly_linked_list_node import SinglyLinkedListNode def is_palindrome(head: Optional[SinglyLinkedListNode]) -> bool: diff --git a/singly_linked_lists/remove_linked_list_elements.py b/singly_linked_lists/remove_linked_list_elements.py index f9f8840..576d17a 100644 --- a/singly_linked_lists/remove_linked_list_elements.py +++ b/singly_linked_lists/remove_linked_list_elements.py @@ -1,8 +1,11 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def remove_elements(head: Optional[SinglyLinkedListNode], data: int) -> Optional[SinglyLinkedListNode]: +def remove_elements( + head: Optional[SinglyLinkedListNode], data: int +) -> Optional[SinglyLinkedListNode]: dummy_node: SinglyLinkedListNode = SinglyLinkedListNode(0) dummy_node.next = head diff --git a/singly_linked_lists/remove_nth_node_from_list.py b/singly_linked_lists/remove_nth_node_from_list.py index 1d2577b..dcd5e9f 100644 --- a/singly_linked_lists/remove_nth_node_from_list.py +++ b/singly_linked_lists/remove_nth_node_from_list.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/reverse_linked_list.py b/singly_linked_lists/reverse_linked_list.py index d88aac7..6b48eaf 100644 --- a/singly_linked_lists/reverse_linked_list.py +++ b/singly_linked_lists/reverse_linked_list.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/reverse_linked_list_recursive.py b/singly_linked_lists/reverse_linked_list_recursive.py index 17869b6..b68095f 100644 --- a/singly_linked_lists/reverse_linked_list_recursive.py +++ b/singly_linked_lists/reverse_linked_list_recursive.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/rotate_list.py b/singly_linked_lists/rotate_list.py index 791c4ce..77e816a 100644 --- a/singly_linked_lists/rotate_list.py +++ b/singly_linked_lists/rotate_list.py @@ -1,8 +1,11 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def rotate_list(head: Optional[SinglyLinkedListNode], amount: int) -> Optional[SinglyLinkedListNode]: +def rotate_list( + head: Optional[SinglyLinkedListNode], amount: int +) -> Optional[SinglyLinkedListNode]: if not head: return None diff --git a/singly_linked_lists/tests/test_add_two_numbers.py b/singly_linked_lists/tests/test_add_two_numbers.py index 6cd0fc0..b5355a8 100644 --- a/singly_linked_lists/tests/test_add_two_numbers.py +++ b/singly_linked_lists/tests/test_add_two_numbers.py @@ -1,5 +1,5 @@ -from singly_linked_lists.add_two_numbers import add_two_numbers from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.add_two_numbers import add_two_numbers from test_helpers.test_helpers import get_list_values diff --git a/singly_linked_lists/tests/test_detect_cycle.py b/singly_linked_lists/tests/test_detect_cycle.py index c2405bc..3de26ab 100644 --- a/singly_linked_lists/tests/test_detect_cycle.py +++ b/singly_linked_lists/tests/test_detect_cycle.py @@ -1,5 +1,5 @@ -from singly_linked_lists.detect_cycle import detect_cycle, detect_cycle_with_set from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.detect_cycle import detect_cycle, detect_cycle_with_set def test_detect_cycle(): diff --git a/singly_linked_lists/tests/test_find_middle_node.py b/singly_linked_lists/tests/test_find_middle_node.py index 079df4a..00b0518 100644 --- a/singly_linked_lists/tests/test_find_middle_node.py +++ b/singly_linked_lists/tests/test_find_middle_node.py @@ -1,5 +1,5 @@ -from singly_linked_lists.find_middle_node import find_middle_node from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.find_middle_node import find_middle_node def test_find_middle_node(): diff --git a/singly_linked_lists/tests/test_intersection_two_linked_lists.py b/singly_linked_lists/tests/test_intersection_two_linked_lists.py index d178e06..60e33c4 100644 --- a/singly_linked_lists/tests/test_intersection_two_linked_lists.py +++ b/singly_linked_lists/tests/test_intersection_two_linked_lists.py @@ -1,5 +1,5 @@ -from singly_linked_lists.intersection_two_linked_lists import get_intersection_node from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.intersection_two_linked_lists import get_intersection_node def test_get_intersection_node(): diff --git a/singly_linked_lists/tests/test_intersection_two_linked_lists_with_set.py b/singly_linked_lists/tests/test_intersection_two_linked_lists_with_set.py index 9a4822a..84358e9 100644 --- a/singly_linked_lists/tests/test_intersection_two_linked_lists_with_set.py +++ b/singly_linked_lists/tests/test_intersection_two_linked_lists_with_set.py @@ -1,5 +1,7 @@ -from singly_linked_lists.intersection_two_linked_lists_with_set import get_intersection_node_with_set from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.intersection_two_linked_lists_with_set import ( + get_intersection_node_with_set, +) def test_get_intersection_node(): diff --git a/singly_linked_lists/tests/test_linked_list_cycle.py b/singly_linked_lists/tests/test_linked_list_cycle.py index 64d0aca..08bf987 100644 --- a/singly_linked_lists/tests/test_linked_list_cycle.py +++ b/singly_linked_lists/tests/test_linked_list_cycle.py @@ -1,5 +1,5 @@ -from singly_linked_lists.linked_list_cycle import has_cycle, has_cycle_with_set from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.linked_list_cycle import has_cycle, has_cycle_with_set def test_has_cycle(): diff --git a/singly_linked_lists/tests/test_merge_k_lists.py b/singly_linked_lists/tests/test_merge_k_lists.py index 248210f..acc2649 100644 --- a/singly_linked_lists/tests/test_merge_k_lists.py +++ b/singly_linked_lists/tests/test_merge_k_lists.py @@ -3,7 +3,11 @@ def test_merge_k_lists(): - lists = [get_singly_linked_list([1, 2, 3]), get_singly_linked_list([1, 3, 4, 5]), get_singly_linked_list([3, 6])] + lists = [ + get_singly_linked_list([1, 2, 3]), + get_singly_linked_list([1, 3, 4, 5]), + get_singly_linked_list([3, 6]), + ] assert get_list_values(merge_k_lists(lists)) == [1, 1, 2, 3, 3, 3, 4, 5, 6] lists = [None, None, get_singly_linked_list([1, 2, 3])] diff --git a/singly_linked_lists/tests/test_merge_two_sorted_lists.py b/singly_linked_lists/tests/test_merge_two_sorted_lists.py index e64945f..2685a37 100644 --- a/singly_linked_lists/tests/test_merge_two_sorted_lists.py +++ b/singly_linked_lists/tests/test_merge_two_sorted_lists.py @@ -1,5 +1,5 @@ -from singly_linked_lists.merge_two_sorted_lists import merge_two_lists from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.merge_two_sorted_lists import merge_two_lists from test_helpers.test_helpers import get_list_values diff --git a/singly_linked_lists/tests/test_remove_linked_list_elements.py b/singly_linked_lists/tests/test_remove_linked_list_elements.py index a278e82..5583206 100644 --- a/singly_linked_lists/tests/test_remove_linked_list_elements.py +++ b/singly_linked_lists/tests/test_remove_linked_list_elements.py @@ -1,5 +1,5 @@ -from singly_linked_lists.remove_linked_list_elements import remove_elements from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.remove_linked_list_elements import remove_elements from test_helpers.test_helpers import get_list_values diff --git a/singly_linked_lists/tests/test_remove_nth_node_from_list.py b/singly_linked_lists/tests/test_remove_nth_node_from_list.py index 2ec9620..0eea15e 100644 --- a/singly_linked_lists/tests/test_remove_nth_node_from_list.py +++ b/singly_linked_lists/tests/test_remove_nth_node_from_list.py @@ -1,5 +1,5 @@ -from singly_linked_lists.remove_nth_node_from_list import remove_nth_from_end from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.remove_nth_node_from_list import remove_nth_from_end def test_remove_nth_from_end(): diff --git a/singly_linked_lists/tests/test_reverse_linked_list.py b/singly_linked_lists/tests/test_reverse_linked_list.py index 7cfabed..f2ea638 100644 --- a/singly_linked_lists/tests/test_reverse_linked_list.py +++ b/singly_linked_lists/tests/test_reverse_linked_list.py @@ -1,5 +1,5 @@ -from singly_linked_lists.reverse_linked_list import reverse_linked_list from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.reverse_linked_list import reverse_linked_list from test_helpers.test_helpers import get_list_values diff --git a/singly_linked_lists/tests/test_reverse_linked_list_recursive.py b/singly_linked_lists/tests/test_reverse_linked_list_recursive.py index 58176cb..d516dd6 100644 --- a/singly_linked_lists/tests/test_reverse_linked_list_recursive.py +++ b/singly_linked_lists/tests/test_reverse_linked_list_recursive.py @@ -1,5 +1,5 @@ -from singly_linked_lists.reverse_linked_list_recursive import reverse_linked_list_recursive from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.reverse_linked_list_recursive import reverse_linked_list_recursive from test_helpers.test_helpers import get_list_values diff --git a/stacks/daily_temperatures.py b/stacks/daily_temperatures.py index 5cf68da..744c65e 100644 --- a/stacks/daily_temperatures.py +++ b/stacks/daily_temperatures.py @@ -1,6 +1,6 @@ -from typing import List from collections import deque from queue import LifoQueue +from typing import List def daily_temperatures_brute_force(temps: List[int]) -> List[int]: diff --git a/stacks/decode_string.py b/stacks/decode_string.py index 3688d6d..42f18de 100644 --- a/stacks/decode_string.py +++ b/stacks/decode_string.py @@ -1,13 +1,11 @@ - - def decode_string(value: str) -> str: stack = [] for char in value: - if char != ']': + if char != "]": stack.append(char) else: - temp_string, num = '', '' - while stack and stack[-1] != '[': + temp_string, num = "", "" + while stack and stack[-1] != "[": temp_string = stack.pop() + temp_string stack.pop() @@ -17,4 +15,4 @@ def decode_string(value: str) -> str: num = int(num) stack.append(temp_string * num) - return ''.join(stack) + return "".join(stack) diff --git a/stacks/polish_notation.py b/stacks/polish_notation.py index b538742..13ecb15 100644 --- a/stacks/polish_notation.py +++ b/stacks/polish_notation.py @@ -1,13 +1,13 @@ from math import trunc -from typing import List from queue import LifoQueue +from typing import List def evaluate_rpn(tokens: List[str]) -> int: stack = LifoQueue() for token in tokens: - if token.lstrip('-').isdigit(): + if token.lstrip("-").isdigit(): stack.put(token) else: right = int(stack.get()) @@ -18,10 +18,10 @@ def evaluate_rpn(tokens: List[str]) -> int: def compute(left: int, right: int, operator: str) -> int: - if operator == '-': + if operator == "-": return left - right - if operator == '+': + if operator == "+": return left + right - if operator == '/': + if operator == "/": return trunc(float(left) / right) return left * right diff --git a/stacks/roman_to_integer.py b/stacks/roman_to_integer.py index 6ba8095..5c965e7 100644 --- a/stacks/roman_to_integer.py +++ b/stacks/roman_to_integer.py @@ -1,12 +1,4 @@ -ROMAN_NUMERALS = { - 'I': 1, - 'V': 5, - 'X': 10, - 'L': 50, - 'C': 100, - 'D': 500, - 'M': 1000 -} +ROMAN_NUMERALS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def roman_to_integer(roman: str) -> int: diff --git a/stacks/stack_with_queue.py b/stacks/stack_with_queue.py index 32f8d94..0fa2ab9 100644 --- a/stacks/stack_with_queue.py +++ b/stacks/stack_with_queue.py @@ -1,11 +1,10 @@ -from typing import Deque, Generic, TypeVar from collections import deque +from typing import Deque, Generic, TypeVar -T = TypeVar('T') +T = TypeVar("T") class Stack(Generic[T]): - def __init__(self): self.stack: Deque[T] = deque() diff --git a/stacks/tests/test_daily_temperatures.py b/stacks/tests/test_daily_temperatures.py index 4ed0fe0..b2271fe 100644 --- a/stacks/tests/test_daily_temperatures.py +++ b/stacks/tests/test_daily_temperatures.py @@ -2,7 +2,16 @@ def test_daily_temperatures_brute_force(): - assert daily_temperatures_brute_force([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0] + assert daily_temperatures_brute_force([73, 74, 75, 71, 69, 72, 76, 73]) == [ + 1, + 1, + 4, + 2, + 1, + 1, + 0, + 0, + ] def test_daily_temperatures(): diff --git a/stacks/tests/test_roman_to_integer.py b/stacks/tests/test_roman_to_integer.py index 0b4c437..617ff74 100644 --- a/stacks/tests/test_roman_to_integer.py +++ b/stacks/tests/test_roman_to_integer.py @@ -2,5 +2,5 @@ def test_roman_to_integer(): - assert roman_to_integer('III') == 3 - assert roman_to_integer('MCMXCIV') == 1994 + assert roman_to_integer("III") == 3 + assert roman_to_integer("MCMXCIV") == 1994 diff --git a/stacks/tests/test_valid_parentheses.py b/stacks/tests/test_valid_parentheses.py index 93f92eb..7293157 100644 --- a/stacks/tests/test_valid_parentheses.py +++ b/stacks/tests/test_valid_parentheses.py @@ -2,9 +2,9 @@ def test_valid_parentheses(): - assert valid_parentheses('()') - assert valid_parentheses('(){}[]') - assert valid_parentheses('{[]}') - assert not valid_parentheses('(]') - assert not valid_parentheses('((') - assert not valid_parentheses('([)]') + assert valid_parentheses("()") + assert valid_parentheses("(){}[]") + assert valid_parentheses("{[]}") + assert not valid_parentheses("(]") + assert not valid_parentheses("((") + assert not valid_parentheses("([)]") diff --git a/stacks/valid_parentheses.py b/stacks/valid_parentheses.py index c9dd037..9bc300a 100644 --- a/stacks/valid_parentheses.py +++ b/stacks/valid_parentheses.py @@ -2,7 +2,7 @@ def valid_parentheses(value: str) -> bool: if len(value) % 2 != 0: return False - closing_values = {'(': ')', '{': '}', '[': ']'} + closing_values = {"(": ")", "{": "}", "[": "]"} stack = [] for char in value: diff --git a/strings/add_binary.py b/strings/add_binary.py index c4292c9..5d2646b 100644 --- a/strings/add_binary.py +++ b/strings/add_binary.py @@ -12,9 +12,9 @@ def add_binary(num1: str, num2: str) -> str: num2 = ("0" * (max_length - length_b)) + num2 for index in range(max_length - 1, -1, -1): - if num1[index] == '1': + if num1[index] == "1": carry += 1 - if num2[index] == '1': + if num2[index] == "1": carry += 1 if carry % 2 == 1: @@ -25,9 +25,9 @@ def add_binary(num1: str, num2: str) -> str: carry //= 2 if carry == 1: - output.appendleft('1') + output.appendleft("1") - return ''.join(output) + return "".join(output) def add_binary_with_builtins(num1: str, num2: str) -> str: diff --git a/strings/anagram.py b/strings/anagram.py index ddff4b7..6ba8c0a 100644 --- a/strings/anagram.py +++ b/strings/anagram.py @@ -1,5 +1,3 @@ - - def valid_anagram(val1: str, val2: str) -> bool: if len(val1) != len(val2): return False diff --git a/strings/crop_string.py b/strings/crop_string.py index f1ca68f..ec418a0 100644 --- a/strings/crop_string.py +++ b/strings/crop_string.py @@ -1,5 +1,3 @@ - - def crop_string(string: str, new_length: int) -> str: length = len(string) last_valid_index = 0 @@ -8,7 +6,7 @@ def crop_string(string: str, new_length: int) -> str: return string for i in range(new_length): - if string[i] == ' ': + if string[i] == " ": last_valid_index = i return string[:last_valid_index] diff --git a/strings/first_unique_character_in_str.py b/strings/first_unique_character_in_str.py index 42e63f5..6e0a06c 100644 --- a/strings/first_unique_character_in_str.py +++ b/strings/first_unique_character_in_str.py @@ -1,5 +1,3 @@ - - def first_unique_character_in_str(val: str) -> int: chars = {} diff --git a/strings/implement_str_str.py b/strings/implement_str_str.py index 271692e..538f138 100644 --- a/strings/implement_str_str.py +++ b/strings/implement_str_str.py @@ -1,5 +1,3 @@ - - def str_str(haystack: str, needle: str) -> int: if not needle: return 0 @@ -8,6 +6,6 @@ def str_str(haystack: str, needle: str) -> int: length_needle = len(needle) for index in range(length_haystack): - if haystack[index:index + length_needle] == needle: + if haystack[index : index + length_needle] == needle: return index return -1 diff --git a/strings/jewels_and_stones.py b/strings/jewels_and_stones.py index 1e9560f..7b06717 100644 --- a/strings/jewels_and_stones.py +++ b/strings/jewels_and_stones.py @@ -1,5 +1,3 @@ - - def jewels_and_stones(jewels: str, stones: str) -> int: stone_count = dict() diff --git a/strings/license_key_formatter.py b/strings/license_key_formatter.py index 3ec11b2..9f1a10a 100644 --- a/strings/license_key_formatter.py +++ b/strings/license_key_formatter.py @@ -1,7 +1,5 @@ - - def license_key_formatter(license_str: str, group_length: int) -> str: - license_keys = license_str.replace('-', '').upper() + license_keys = license_str.replace("-", "").upper() remainder = len(license_keys) % group_length start = 0 @@ -13,4 +11,4 @@ def license_key_formatter(license_str: str, group_length: int) -> str: start = end end += group_length - return '-'.join(license_groups) + return "-".join(license_groups) diff --git a/strings/longest_common_prefix.py b/strings/longest_common_prefix.py index 5e8f405..57aa9e2 100644 --- a/strings/longest_common_prefix.py +++ b/strings/longest_common_prefix.py @@ -16,7 +16,7 @@ def longest_common_prefix_horizontal(strings: List[str]) -> str: break last_match = char_index # Add 1 to end index since last index in slice is exclusive - longest = strings[index][0:last_match + 1] + longest = strings[index][0 : last_match + 1] return longest @@ -33,7 +33,7 @@ def longest_common_prefix_vertical(strings: List[str]) -> str: if index > len(prefix) - 1: return prefix if index > len(strings[string_index]) - 1: - prefix = prefix[:len(strings[string_index])] + prefix = prefix[: len(strings[string_index])] continue if strings[string_index][index] != prefix[index]: prefix = strings[string_index][:index] diff --git a/strings/longest_substring_without_duplicates.py b/strings/longest_substring_without_duplicates.py index 28260fb..7a62b79 100644 --- a/strings/longest_substring_without_duplicates.py +++ b/strings/longest_substring_without_duplicates.py @@ -1,5 +1,3 @@ - - def longest_substring_without_duplicates(string: str) -> int: length = len(string) if length <= 1: diff --git a/strings/multiply_strings.py b/strings/multiply_strings.py index 26c7e1e..0aa6282 100644 --- a/strings/multiply_strings.py +++ b/strings/multiply_strings.py @@ -1,9 +1,7 @@ - - def multiply_strings(num1: str, num2: str) -> str: def string_to_int(string: str) -> int: length = len(string) - zero = ord('0') + zero = ord("0") value = 0 for index in range(length): diff --git a/strings/palindrome.py b/strings/palindrome.py index 0d1bc73..10ee973 100644 --- a/strings/palindrome.py +++ b/strings/palindrome.py @@ -1,5 +1,3 @@ - - def valid_palindrome_naive(string: str) -> bool: return string == string[::-1] diff --git a/strings/pangram.py b/strings/pangram.py index f32f007..4a98972 100644 --- a/strings/pangram.py +++ b/strings/pangram.py @@ -1,5 +1,3 @@ - - def pangram(string: str) -> bool: alpha_set = set() diff --git a/strings/reverse_string.py b/strings/reverse_string.py index f3200d5..6967ce2 100644 --- a/strings/reverse_string.py +++ b/strings/reverse_string.py @@ -15,11 +15,11 @@ def reverse_string_in_place(string: [str]): def reverse_string_with_list_comprehension(string: str) -> str: - return ''.join([string[i] for i in range(len(string) - 1, -1, -1)]) + return "".join([string[i] for i in range(len(string) - 1, -1, -1)]) def reverse_string_with_loop(string: str) -> str: reversed_str: List[Optional[str]] = [None] * len(string) for index in range(len(string) - 1, -1, -1): reversed_str[len(string) - 1 - index] = string[index] - return ''.join(reversed_str) + return "".join(reversed_str) diff --git a/strings/reverse_words.py b/strings/reverse_words.py index 72d62a0..4704fd9 100644 --- a/strings/reverse_words.py +++ b/strings/reverse_words.py @@ -13,11 +13,11 @@ def reverse(array: List[str], left: int, right: int): left_index = 0 for index in range(length): - if sentence_array[index] == ' ': + if sentence_array[index] == " ": reverse(sentence_array, left_index, index - 1) left_index = index + 1 # reverse last word, or sentence if one word reverse(sentence_array, left_index, length - 1) - return ''.join(sentence_array) + return "".join(sentence_array) diff --git a/strings/run_length_encoding.py b/strings/run_length_encoding.py index 6b6b858..8a8993c 100644 --- a/strings/run_length_encoding.py +++ b/strings/run_length_encoding.py @@ -1,5 +1,3 @@ - - def run_length_encoding(string: str) -> str: counter = 0 current_character = None @@ -10,11 +8,11 @@ def run_length_encoding(string: str) -> str: counter += 1 else: if current_character: - output.append(current_character + str(counter if counter > 1 else '')) + output.append(current_character + str(counter if counter > 1 else "")) current_character = character counter = 1 if current_character: - output.append(current_character + str(counter if counter > 1 else '')) + output.append(current_character + str(counter if counter > 1 else "")) - return ''.join(output) + return "".join(output) diff --git a/strings/string_to_integer.py b/strings/string_to_integer.py index c6411f2..2a907c2 100644 --- a/strings/string_to_integer.py +++ b/strings/string_to_integer.py @@ -1,8 +1,6 @@ - - def string_to_integer(string: str) -> int: length = len(string) - numbers = set(list('1234567890')) + numbers = set(list("1234567890")) positive = True start_index = -1 @@ -10,10 +8,10 @@ def string_to_integer(string: str) -> int: return 0 for index in range(length): - if string[index] in ' ': + if string[index] in " ": continue - if string[index] in '-': + if string[index] in "-": positive = False continue @@ -36,4 +34,4 @@ def string_to_integer(string: str) -> int: else: break - return int(string[start_index: end_index]) if positive else -int(string[start_index: end_index]) + return int(string[start_index:end_index]) if positive else -int(string[start_index:end_index]) diff --git a/strings/string_to_integer_ii.py b/strings/string_to_integer_ii.py index 37f2d83..fa76916 100644 --- a/strings/string_to_integer_ii.py +++ b/strings/string_to_integer_ii.py @@ -1,7 +1,5 @@ - - def string_to_integer_ii(string: str) -> int: - zero = ord('0') + zero = ord("0") positive = True length = len(string) start = 0 @@ -11,10 +9,10 @@ def string_to_integer_ii(string: str) -> int: return 0 # Determine Positive / Negative - if string[0] == '-': + if string[0] == "-": start = 1 positive = False - elif string[0] == '+': + elif string[0] == "+": start = 1 # Iterate over remaining characters diff --git a/strings/tests/palindrome_permutation.py b/strings/tests/palindrome_permutation.py index e1032a8..1d917ca 100644 --- a/strings/tests/palindrome_permutation.py +++ b/strings/tests/palindrome_permutation.py @@ -2,9 +2,9 @@ def test_palindrome_permutation(): - assert palindrome_permutation('aabb') - assert palindrome_permutation('aab') - assert palindrome_permutation('aba') - assert palindrome_permutation('') - assert not palindrome_permutation('test') - assert not palindrome_permutation('aabc') + assert palindrome_permutation("aabb") + assert palindrome_permutation("aab") + assert palindrome_permutation("aba") + assert palindrome_permutation("") + assert not palindrome_permutation("test") + assert not palindrome_permutation("aabc") diff --git a/strings/tests/test_crop_string.py b/strings/tests/test_crop_string.py index 22ce24f..fea00b5 100644 --- a/strings/tests/test_crop_string.py +++ b/strings/tests/test_crop_string.py @@ -2,9 +2,9 @@ def test_crop_string(): - assert crop_string('test', 9) == 'test' - assert crop_string('test', 3) == '' - assert crop_string('test', 4) == 'test' - assert crop_string('test test', 6) == 'test' - assert crop_string('', 4) == '' - assert crop_string('test test', 9) == 'test test' + assert crop_string("test", 9) == "test" + assert crop_string("test", 3) == "" + assert crop_string("test", 4) == "test" + assert crop_string("test test", 6) == "test" + assert crop_string("", 4) == "" + assert crop_string("test test", 9) == "test test" diff --git a/strings/tests/test_first_unique_character_in_str.py b/strings/tests/test_first_unique_character_in_str.py index 08c06a3..c33889f 100644 --- a/strings/tests/test_first_unique_character_in_str.py +++ b/strings/tests/test_first_unique_character_in_str.py @@ -2,11 +2,11 @@ def test_first_unique_character(): - string = 'abc' + string = "abc" assert first_unique_character_in_str(string) == 0 - string = 'eee' + string = "eee" assert first_unique_character_in_str(string) == -1 - string = 'aba' + string = "aba" assert first_unique_character_in_str(string) == 1 diff --git a/strings/tests/test_group_anagrams.py b/strings/tests/test_group_anagrams.py index 45ca7ad..32faf36 100644 --- a/strings/tests/test_group_anagrams.py +++ b/strings/tests/test_group_anagrams.py @@ -5,8 +5,8 @@ def test_group_anagrams(): strings = [] assert group_anagrams(strings) == [] - strings = ['test'] - assert group_anagrams(strings) == [['test']] + strings = ["test"] + assert group_anagrams(strings) == [["test"]] - strings = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat'] - assert group_anagrams(strings) == [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']] + strings = ["eat", "tea", "tan", "ate", "nat", "bat"] + assert group_anagrams(strings) == [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]] diff --git a/strings/tests/test_implement_str_str.py b/strings/tests/test_implement_str_str.py index 98f9ba4..170e9e0 100644 --- a/strings/tests/test_implement_str_str.py +++ b/strings/tests/test_implement_str_str.py @@ -2,8 +2,8 @@ def test_str_str(): - assert str_str('hello', 'll') == 2 - assert str_str('test', '') == 0 - assert str_str('foo', 'bar') == -1 - assert str_str('a', 'aa') == -1 - assert str_str('aaa', 'a') == 0 + assert str_str("hello", "ll") == 2 + assert str_str("test", "") == 0 + assert str_str("foo", "bar") == -1 + assert str_str("a", "aa") == -1 + assert str_str("aaa", "a") == 0 diff --git a/strings/tests/test_license_key_formatter.py b/strings/tests/test_license_key_formatter.py index 995c0ff..902342e 100644 --- a/strings/tests/test_license_key_formatter.py +++ b/strings/tests/test_license_key_formatter.py @@ -2,7 +2,7 @@ def test_license_key_formatter(): - assert license_key_formatter('5F3Z-2e-9-w', 4) == '5F3Z-2E9W' - assert license_key_formatter('5F3Z-2e-9-w', 3) == '5F-3Z2-E9W' - assert license_key_formatter('TES-T', 4) == 'TEST' - assert license_key_formatter('t-est', 2) == 'TE-ST' + assert license_key_formatter("5F3Z-2e-9-w", 4) == "5F3Z-2E9W" + assert license_key_formatter("5F3Z-2e-9-w", 3) == "5F-3Z2-E9W" + assert license_key_formatter("TES-T", 4) == "TEST" + assert license_key_formatter("t-est", 2) == "TE-ST" diff --git a/strings/tests/test_longest_common_prefix.py b/strings/tests/test_longest_common_prefix.py index 67ed436..a830be7 100644 --- a/strings/tests/test_longest_common_prefix.py +++ b/strings/tests/test_longest_common_prefix.py @@ -1,4 +1,7 @@ -from strings.longest_common_prefix import longest_common_prefix_horizontal, longest_common_prefix_vertical +from strings.longest_common_prefix import ( + longest_common_prefix_horizontal, + longest_common_prefix_vertical, +) def test_longest_common_prefix_horizontal(): diff --git a/strings/tests/test_longest_substring_without_duplicates.py b/strings/tests/test_longest_substring_without_duplicates.py index af0afcf..cfff4b2 100644 --- a/strings/tests/test_longest_substring_without_duplicates.py +++ b/strings/tests/test_longest_substring_without_duplicates.py @@ -1,9 +1,8 @@ -from strings.longest_substring_without_duplicates \ - import longest_substring_without_duplicates +from strings.longest_substring_without_duplicates import longest_substring_without_duplicates def test_longest_substring_without_duplicates(): - assert longest_substring_without_duplicates('abcabcbb') == 3 - assert longest_substring_without_duplicates('abc') == 3 - assert longest_substring_without_duplicates('abca') == 3 - assert longest_substring_without_duplicates('abadc') == 4 + assert longest_substring_without_duplicates("abcabcbb") == 3 + assert longest_substring_without_duplicates("abc") == 3 + assert longest_substring_without_duplicates("abca") == 3 + assert longest_substring_without_duplicates("abadc") == 4 diff --git a/strings/tests/test_multiply_strings.py b/strings/tests/test_multiply_strings.py index 2cb9ca5..afea7d1 100644 --- a/strings/tests/test_multiply_strings.py +++ b/strings/tests/test_multiply_strings.py @@ -2,5 +2,5 @@ def test_multiply_strings(): - assert multiply_strings('2', '3') == '6' - assert multiply_strings('123', '456') == '56088' + assert multiply_strings("2", "3") == "6" + assert multiply_strings("123", "456") == "56088" diff --git a/strings/tests/test_palindrome.py b/strings/tests/test_palindrome.py index bca4841..30259a5 100644 --- a/strings/tests/test_palindrome.py +++ b/strings/tests/test_palindrome.py @@ -2,9 +2,9 @@ def test_valid_palindrome_naive(): - val1 = 'aba' - val2 = 'aacbaa' - val3 = 'a:bba' + val1 = "aba" + val2 = "aacbaa" + val3 = "a:bba" assert valid_palindrome_naive(val1) assert not valid_palindrome_naive(val2) @@ -12,9 +12,9 @@ def test_valid_palindrome_naive(): def test_valid_palindrome(): - val1 = 'aba' - val2 = 'aacbaa' - val3 = 'a:bba' + val1 = "aba" + val2 = "aacbaa" + val3 = "a:bba" assert valid_palindrome(val1) assert not valid_palindrome(val2) diff --git a/strings/tests/test_pangram.py b/strings/tests/test_pangram.py index bc81fce..db68f13 100644 --- a/strings/tests/test_pangram.py +++ b/strings/tests/test_pangram.py @@ -2,8 +2,8 @@ def test_pangram(): - assert pangram('Mr. Jock, TV quiz PhD., bags few lynx.') - assert pangram('abcdefghijklmnopqrstuvwxyz') - assert not pangram('test') - assert not pangram('') + assert pangram("Mr. Jock, TV quiz PhD., bags few lynx.") + assert pangram("abcdefghijklmnopqrstuvwxyz") + assert not pangram("test") + assert not pangram("") assert pangram(" \n\t!@#$%^&*()_+[]/\\;',./abcdefghijklmnopqrstuvwxyz") diff --git a/strings/tests/test_reverse_string.py b/strings/tests/test_reverse_string.py index cefe378..2f098ef 100644 --- a/strings/tests/test_reverse_string.py +++ b/strings/tests/test_reverse_string.py @@ -1,22 +1,24 @@ -from strings.reverse_string import \ - reverse_string, reverse_string_in_place, \ - reverse_string_with_list_comprehension, \ - reverse_string_with_loop +from strings.reverse_string import ( + reverse_string, + reverse_string_in_place, + reverse_string_with_list_comprehension, + reverse_string_with_loop, +) def test_reverse_string(): - assert reverse_string('test') == 'tset' + assert reverse_string("test") == "tset" def test_reverse_string_inplace(): - string = ['t', 'e', 's', 't'] + string = ["t", "e", "s", "t"] reverse_string_in_place(string) - assert string == ['t', 's', 'e', 't'] + assert string == ["t", "s", "e", "t"] def test_reverse_string_with_list_comprehension(): - assert reverse_string_with_list_comprehension('test') == 'tset' + assert reverse_string_with_list_comprehension("test") == "tset" def test_reverse_with_loop(): - assert reverse_string_with_loop('test') == 'tset' + assert reverse_string_with_loop("test") == "tset" diff --git a/strings/tests/test_reverse_words.py b/strings/tests/test_reverse_words.py index c5c1aa0..2665980 100644 --- a/strings/tests/test_reverse_words.py +++ b/strings/tests/test_reverse_words.py @@ -2,7 +2,7 @@ def test_reverse_words(): - assert reverse_words('foo bar baz') == 'oof rab zab' - assert reverse_words('foo') == 'oof' - assert reverse_words('') == '' - assert reverse_words('a b') == 'a b' + assert reverse_words("foo bar baz") == "oof rab zab" + assert reverse_words("foo") == "oof" + assert reverse_words("") == "" + assert reverse_words("a b") == "a b" diff --git a/strings/tests/test_run_length_encoding.py b/strings/tests/test_run_length_encoding.py index 7743bc2..4d7d983 100644 --- a/strings/tests/test_run_length_encoding.py +++ b/strings/tests/test_run_length_encoding.py @@ -2,7 +2,7 @@ def test_run_length_encoding(): - assert run_length_encoding('abc') == 'abc' - assert run_length_encoding('aaabbcddd') == 'a3b2cd3' - assert run_length_encoding('abbbbc') == 'ab4c' - assert run_length_encoding('') == '' + assert run_length_encoding("abc") == "abc" + assert run_length_encoding("aaabbcddd") == "a3b2cd3" + assert run_length_encoding("abbbbc") == "ab4c" + assert run_length_encoding("") == "" diff --git a/strings/tests/test_unique_emails.py b/strings/tests/test_unique_emails.py index 6fc3589..51ee360 100644 --- a/strings/tests/test_unique_emails.py +++ b/strings/tests/test_unique_emails.py @@ -6,6 +6,6 @@ def test_unique_email_addresses(): "test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com", "testemail+david@lee.tcode.com", - "testemail@leetcode.com" + "testemail@leetcode.com", ] assert unique_email_addresses(emails) == 2 diff --git a/strings/unique_emails.py b/strings/unique_emails.py index 72a1c35..230a58e 100644 --- a/strings/unique_emails.py +++ b/strings/unique_emails.py @@ -8,16 +8,16 @@ def unique_email_addresses(emails: List[str]) -> int: normalized_email = [] for index, string in enumerate(email): - if string == '+': - at_index = email.index('@', index) + if string == "+": + at_index = email.index("@", index) normalized_email.append(email[at_index:]) - unique_emails.add(''.join(normalized_email)) + unique_emails.add("".join(normalized_email)) break - if string == '.': + if string == ".": continue - if string == '@': + if string == "@": normalized_email.append(email[index:]) - unique_emails.add(''.join(normalized_email)) + unique_emails.add("".join(normalized_email)) break normalized_email.append(string) diff --git a/strings/valid_word_abbreviation.py b/strings/valid_word_abbreviation.py index a79bceb..1554126 100644 --- a/strings/valid_word_abbreviation.py +++ b/strings/valid_word_abbreviation.py @@ -1,5 +1,3 @@ - - def valid_word_abbreviation(word: str, abbr: str) -> bool: num = "" abbr_index = 0 diff --git a/test_helpers/test_helpers.py b/test_helpers/test_helpers.py index ec34dd8..171ae2f 100644 --- a/test_helpers/test_helpers.py +++ b/test_helpers/test_helpers.py @@ -1,10 +1,11 @@ from collections import deque from typing import List, TypeVar -from data_structures.singly_linked_list_node import SinglyLinkedListNode + from binary_tree.tree_node import TreeNode +from data_structures.singly_linked_list_node import SinglyLinkedListNode from n_ary_tree.nary_tree_node import NaryTreeNode -T = TypeVar('T') +T = TypeVar("T") def get_binary_search_tree(): diff --git a/tests/data_structures/test_min_heap.py b/tests/data_structures/test_min_heap.py new file mode 100644 index 0000000..ed20ec8 --- /dev/null +++ b/tests/data_structures/test_min_heap.py @@ -0,0 +1,55 @@ +from data_structures.min_heap import MinHeap + + +def test_min_heap_init(): + min_heap = MinHeap() + assert min_heap.size() == 0 + + +def test_min_heap_insert(): + min_heap = MinHeap() + min_heap.insert(12) + min_heap.insert(13) + min_heap.insert(11) + min_heap.insert(4) + min_heap.insert(20) + min_heap.insert(9) + min_heap.insert(22) + min_heap.insert(14) + assert min_heap.values() == [4, 11, 9, 13, 20, 12, 22, 14] + + +def test_min_heap_is_empty(): + min_heap = MinHeap() + assert min_heap.is_empty() + + min_heap.insert(1) + assert not min_heap.is_empty() + + +def test_min_heap_size(): + min_heap = MinHeap() + assert min_heap.size() == 0 + + min_heap.insert(12) + assert min_heap.size() == 1 + + min_heap.insert(13) + assert min_heap.size() == 2 + + min_heap.insert(11) + assert min_heap.size() == 3 + + +def test_min_heap_values(): + min_heap = MinHeap() + assert min_heap.values() == [] + + min_heap.insert(12) + assert min_heap.values() == [12] + + min_heap.insert(13) + assert min_heap.values() == [12, 13] + + min_heap.insert(11) + assert min_heap.values() == [11, 13, 12] diff --git a/trie/map_sum.py b/trie/map_sum.py index 3569164..5836cde 100644 --- a/trie/map_sum.py +++ b/trie/map_sum.py @@ -42,4 +42,4 @@ def __recursive_sum(self, parent_node) -> int: class MapSumNode: def __init__(self, value: int = 0): self.value = value - self.nodes: Dict[str: MapSumNode] = dict() + self.nodes: Dict[str:MapSumNode] = dict() diff --git a/trie/replace_words.py b/trie/replace_words.py index 2054901..41adb4b 100644 --- a/trie/replace_words.py +++ b/trie/replace_words.py @@ -2,7 +2,7 @@ def replace_words(dictionary: List[str], sentence: str) -> str: - words = sentence.split(' ') + words = sentence.split(" ") updated_sentence: [str] = [] prefix_trie = TrieNode() @@ -12,12 +12,12 @@ def replace_words(dictionary: List[str], sentence: str) -> str: for word in words: updated_sentence.append(prefix_trie.replace_word(word)) - return ' '.join(updated_sentence) + return " ".join(updated_sentence) class TrieNode: def __init__(self): - self.nodes: Dict[str: TrieNode] = dict() + self.nodes: Dict[str:TrieNode] = dict() def insert(self, word: str) -> None: current_node = self diff --git a/trie/tests/test_map_sum.py b/trie/tests/test_map_sum.py index c0df70b..0d10edb 100644 --- a/trie/tests/test_map_sum.py +++ b/trie/tests/test_map_sum.py @@ -3,8 +3,8 @@ def test_map_sum(): map_sum = MapSum() - assert map_sum.insert('apple', 3) is None - assert map_sum.sum('ap') == 3 - assert map_sum.sum('apples') == 0 - assert map_sum.insert('app', 2) is None - assert map_sum.sum('ap') == 5 + assert map_sum.insert("apple", 3) is None + assert map_sum.sum("ap") == 3 + assert map_sum.sum("apples") == 0 + assert map_sum.insert("app", 2) is None + assert map_sum.sum("ap") == 5 diff --git a/trie/tests/test_replace_words.py b/trie/tests/test_replace_words.py index a3e268d..3a7a13d 100644 --- a/trie/tests/test_replace_words.py +++ b/trie/tests/test_replace_words.py @@ -2,7 +2,7 @@ def test_replace_words(): - new_words = ['ca', 'cat', 'battle', 'bat', 'rat'] - sentence = 'the cattle was rattled by the battery' - output = 'the ca was rat by the bat' + new_words = ["ca", "cat", "battle", "bat", "rat"] + sentence = "the cattle was rattled by the battery" + output = "the ca was rat by the bat" assert replace_words(new_words, sentence) == output