repo_name
stringclasses
25 values
repo_full_name
stringclasses
25 values
owner
stringclasses
25 values
stars
int64
117k
496k
license
stringclasses
7 values
repo_description
stringclasses
25 values
filepath
stringlengths
9
75
file_type
stringclasses
3 values
language
stringclasses
2 values
content
stringlengths
24
383k
size_bytes
int64
25
387k
num_lines
int64
2
4.44k
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\floor_and_ceiling.py
python
Python
""" In a binary search tree (BST): * The floor of key 'k' is the maximum value that is smaller than or equal to 'k'. * The ceiling of key 'k' is the minimum value that is greater than or equal to 'k'. Reference: https://bit.ly/46uB0a2 Author : Arunkumar Date : 14th October 2023 """ from __future__ import annotations...
2,198
89
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\inorder_tree_traversal_2022.py
python
Python
""" Illustrate how to implement inorder traversal in binary search tree. Author: Gurneet Singh https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/ """ class BinaryTreeNode: """Defining the structure of BinaryTreeNode""" def __init__(self, data: int) -> None: self.data = data...
2,354
83
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\is_sorted.py
python
Python
""" Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid binary search tree is defined as follows: - The left subtree of a node contains only nodes with keys less than the node's key. - The right subtree of a node contains only nodes with keys greater than the node's key. - Bot...
3,142
99
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\is_sum_tree.py
python
Python
""" Is a binary tree a sum tree where the value of every non-leaf node is equal to the sum of the values of its left and right subtrees? https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree """ from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass ...
4,288
163
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\lazy_segment_tree.py
python
Python
from __future__ import annotations import math class SegmentTree: def __init__(self, size: int) -> None: self.size = size # approximate the overall size of segment tree with given value self.segment_tree = [0 for i in range(4 * size)] # create array to store lazy update se...
4,983
137
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\lowest_common_ancestor.py
python
Python
# https://en.wikipedia.org/wiki/Lowest_common_ancestor # https://en.wikipedia.org/wiki/Breadth-first_search from __future__ import annotations from queue import Queue def swap(a: int, b: int) -> tuple[int, int]: """ Return a tuple (b, a) when given two integers a and b >>> swap(2,3) (3, 2) >>> s...
5,170
172
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\maximum_fenwick_tree.py
python
Python
class MaxFenwickTree: """ Maximum Fenwick Tree More info: https://cp-algorithms.com/data_structures/fenwick.html --------- >>> ft = MaxFenwickTree(5) >>> ft.query(0, 5) 0 >>> ft.update(4, 100) >>> ft.query(0, 5) 100 >>> ft.update(4, 0) >>> ft.update(2, 20) >>> ft.que...
2,867
115
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\maximum_sum_bst.py
python
Python
from __future__ import annotations import sys from dataclasses import dataclass INT_MIN = -sys.maxsize + 1 INT_MAX = sys.maxsize - 1 @dataclass class TreeNode: val: int = 0 left: TreeNode | None = None right: TreeNode | None = None def max_sum_bst(root: TreeNode | None) -> int: """ The solutio...
2,221
79
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\merge_two_binary_trees.py
python
Python
#!/usr/local/bin/python3 """ Problem Description: Given two binary tree, return the merged tree. The rule for merging is that if two nodes overlap, then put the value sum of both nodes to the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. """ from __future__ import ann...
2,379
95
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\mirror_binary_tree.py
python
Python
""" Given the root of a binary tree, mirror the tree, and return its root. Leetcode problem reference: https://leetcode.com/problems/mirror-binary-tree/ """ from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: """ A Node has value ...
3,654
161
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\non_recursive_segment_tree.py
python
Python
""" A non-recursive Segment Tree implementation with range query and single element update, works virtually with any list of the same type of elements with a "commutative" combiner. Explanation: https://www.geeksforgeeks.org/iterative-segment-tree-range-minimum-query/ https://www.geeksforgeeks.org/segment-tree-efficie...
4,909
164
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\number_of_possible_binary_trees.py
python
Python
""" Hey, we are going to find an exciting number called Catalan number which is use to find the number of possible binary search trees from tree of a given number of nodes. We will use the formula: t(n) = SUMMATION(i = 1 to n)t(i-1)t(n-i) Further details at Wikipedia: https://en.wikipedia.org/wiki/Catalan_number """ ...
2,991
103
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\README.md
readme
Markdown
# Binary Tree Traversal ## Overview The combination of binary trees being data structures and traversal being an algorithm relates to classic problems, either directly or indirectly. > If you can grasp the traversal of binary trees, the traversal of other complicated trees will be easy for you. The following are so...
5,613
112
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\red_black_tree.py
python
Python
from __future__ import annotations from collections.abc import Iterator class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting no...
25,467
717
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\segment_tree.py
python
Python
import math class SegmentTree: def __init__(self, a): self.A = a self.N = len(self.A) self.st = [0] * ( 4 * self.N ) # approximate the overall size of segment tree with array N if self.N: self.build(1, 0, self.N - 1) def left(self, idx): ...
3,392
117
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\segment_tree_other.py
python
Python
""" Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ from collections.abc import Sequence from queue import Queue class SegmentTreeNode: def __init__(self, start, end, val, left=None, ri...
7,781
238
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\serialize_deserialize_binary_tree.py
python
Python
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class TreeNode: """ A binary tree node has a value, left child, and right child. Props: value: The value of the node. left: The left child of the node. right: The ...
3,701
141
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\symmetric_tree.py
python
Python
""" Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Leetcode reference: https://leetcode.com/problems/symmetric-tree/ """ from __future__ import annotations from dataclasses import dataclass @dataclass class Node: """ A Node represents an element...
3,795
160
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\treap.py
python
Python
from __future__ import annotations from random import random class Node: """ Treap's node Treap is a binary tree by value and heap by priority """ def __init__(self, value: int | None = None): self.value = value self.prior = random() self.left: Node | None = None ...
4,930
180
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\binary_tree\wavelet_tree.py
python
Python
""" Wavelet tree is a data-structure designed to efficiently answer various range queries for arrays. Wavelets trees are different from other binary trees in the sense that the nodes are split based on the actual values of the elements and not on indices, such as the with segment trees or fenwick trees. You can read mo...
6,275
211
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\disjoint_set\alternate_disjoint_set.py
python
Python
""" Implements a disjoint set using Lists and some added heuristics for efficiency Union by Rank Heuristic and Path Compression """ class DisjointSet: def __init__(self, set_counts: list) -> None: """ Initialize with a list of the number of items in each set and with rank = 1 for each set ...
2,260
69
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\disjoint_set\disjoint_set.py
python
Python
""" Disjoint set. Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure """ class Node: def __init__(self, data: int) -> None: self.data = data self.rank: int self.parent: Node def make_set(x: Node) -> None: """ Make x as a set. """ # rank is the distance f...
1,920
86
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\hashing\bloom_filter.py
python
Python
""" See https://en.wikipedia.org/wiki/Bloom_filter The use of this data structure is to test membership in a set. Compared to Python's built-in set() it is more space-efficient. In the following example, only 8 bits of memory will be used: >>> bloom = Bloom(size=8) Initially, the filter contains all zeros: >>> bloom....
2,903
107
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\hashing\double_hash.py
python
Python
#!/usr/bin/env python3 """ Double hashing is a collision resolving technique in Open Addressed Hash tables. Double hashing uses the idea of applying a second hash function to key when a collision occurs. The advantage of Double hashing is that it is one of the best form of probing, producing a uniform distribution of ...
2,822
87
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\hashing\hash_map.py
python
Python
""" Hash map with open addressing. https://en.wikipedia.org/wiki/Hash_table Another hash map implementation, with a good explanation. Modern Dictionaries by Raymond Hettinger https://www.youtube.com/watch?v=p33CVV29OG8 """ from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from ty...
9,057
328
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\hashing\hash_table.py
python
Python
#!/usr/bin/env python3 from abc import abstractmethod from .number_theory.prime_numbers import next_prime class HashTable: """ Basic Hash Table example with open addressing and linear probing """ def __init__( self, size_table: int, charge_factor: int | None = None, l...
8,320
284
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\hashing\hash_table_with_linked_list.py
python
Python
from collections import deque from .hash_table import HashTable class HashTableWithLinkedList(HashTable): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _set_value(self, key, data): self.values[key] = deque() if self.values[key] is None else self.values[key] ...
871
28
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\hashing\number_theory\prime_numbers.py
python
Python
#!/usr/bin/env python3 """ module to operations with prime numbers """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_...
1,344
60
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\hashing\quadratic_probing.py
python
Python
#!/usr/bin/env python3 from .hash_table import HashTable class QuadraticProbing(HashTable): """ Basic Hash Table example with open addressing using Quadratic Probing """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _collision_resolution(self, key, data=None...
2,449
85
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\hashing\tests\test_hash_map.py
test
Python
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _get(k): return getitem, k def _set(k, v): return setitem, k, v def _del(k): return delitem, k def _run_operation(obj, fun, *args): try: return fun(obj, *args), None ...
2,384
98
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\heap\binomial_heap.py
python
Python
""" Binomial Heap Reference: Advanced Data Structures, Peter Brass """ class Node: """ Node in a doubly-linked binomial tree, containing: - value - size of left subtree - link to left, right and parent nodes """ def __init__(self, val): self.val = val # Number ...
12,648
402
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\heap\heap.py
python
Python
from __future__ import annotations from abc import abstractmethod from collections.abc import Iterable from typing import Protocol, TypeVar class Comparable(Protocol): @abstractmethod def __lt__(self: T, other: T) -> bool: pass @abstractmethod def __gt__(self: T, other: T) -> bool: p...
7,666
277
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\heap\heap_generic.py
python
Python
from collections.abc import Callable class Heap: """ A generic Heap class, can be used as min or max by passing the key function accordingly. """ def __init__(self, key: Callable | None = None) -> None: # Stores actual heap items. self.arr: list = [] # Stores indexes of ea...
6,000
175
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\heap\max_heap.py
python
Python
class BinaryHeap: """ A max-heap implementation in Python >>> binary_heap = BinaryHeap() >>> binary_heap.insert(6) >>> binary_heap.insert(10) >>> binary_heap.insert(15) >>> binary_heap.insert(12) >>> binary_heap.pop() 15 >>> binary_heap.pop() 12 >>> binary_heap.get_list ...
2,499
87
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\heap\min_heap.py
python
Python
# Min heap data structure # with decrease key functionality - in O(log(n)) time class Node: def __init__(self, name, val): self.name = name self.val = val def __str__(self): return f"{self.__class__.__name__}({self.name}, {self.val})" def __lt__(self, other): return self....
4,677
171
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\heap\randomized_heap.py
python
Python
#!/usr/bin/env python3 from __future__ import annotations import random from collections.abc import Iterable from typing import Any, TypeVar T = TypeVar("T", bound=bool) class RandomizedHeapNode[T: bool]: """ One node of the randomized heap. Contains the value and references to two children. """ ...
5,519
223
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\heap\skew_heap.py
python
Python
#!/usr/bin/env python3 from __future__ import annotations from collections.abc import Iterable, Iterator from typing import Any, TypeVar T = TypeVar("T", bound=bool) class SkewNode[T: bool]: """ One node of the skew heap. Contains the value and references to two children. """ def __init__(self...
5,869
238
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\kd_tree\build_kdtree.py
python
Python
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11532 # https://github.com/TheAlgorithms/Python/pull/11532 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! from data_structures.kd_tree.kd_node imp...
1,346
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\kd_tree\example\example_usage.py
python
Python
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11532 # https://github.com/TheAlgorithms/Python/pull/11532 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! import numpy as np from data_structures...
1,621
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\kd_tree\example\hypercube_points.py
python
Python
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11532 # https://github.com/TheAlgorithms/Python/pull/11532 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! import numpy as np def hypercube_point...
938
30
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\kd_tree\kd_node.py
python
Python
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11532 # https://github.com/TheAlgorithms/Python/pull/11532 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! from __future__ import annotations cla...
1,072
39
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\kd_tree\nearest_neighbour_search.py
python
Python
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11532 # https://github.com/TheAlgorithms/Python/pull/11532 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! from data_structures.kd_tree.kd_node imp...
2,836
80
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\kd_tree\tests\test_kdtree.py
test
Python
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11532 # https://github.com/TheAlgorithms/Python/pull/11532 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! import numpy as np import pytest from d...
3,332
109
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\__init__.py
python
Python
""" Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: - Head Node: First node, the address of the head node gives us access of the complete list - Last node: points to null """ from __future__ import annotations from typing import Any class Node: def _...
3,893
134
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\circular_linked_list.py
python
Python
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from typing import Any @dataclass class Node: data: Any next_node: Node | None = None @dataclass class CircularLinkedList: head: Node | None = None # Reference to the head (first node) tail: N...
7,067
211
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\deque_doubly.py
python
Python
""" Implementing Deque using DoublyLinkedList ... Operations: 1. insertion in the front -> O(1) 2. insertion in the end -> O(1) 3. remove from the front -> O(1) 4. remove from the end -> O(1) """ class _DoublyLinkedBase: """A Private class (to be inherited)""" class _Node: __slots__ =...
4,216
144
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\doubly_linked_list.py
python
Python
""" https://en.wikipedia.org/wiki/Doubly_linked_list """ class Node: def __init__(self, data): self.data = data self.previous = None self.next = None def __str__(self): return f"{self.data}" class DoublyLinkedList: def __init__(self): self.head = None sel...
6,949
231
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\doubly_linked_list_two.py
python
Python
""" - A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes. - This is an example of a double ended, doubly linked list. - Each link references the next link and the previous one. - A Doubly Linked List (DLL) contains an extra pointer, typically called previous ...
7,169
264
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\floyds_cycle_detection.py
python
Python
""" Floyd's cycle detection algorithm is a popular algorithm used to detect cycles in a linked list. It uses two pointers, a slow pointer and a fast pointer, to traverse the linked list. The slow pointer moves one node at a time while the fast pointer moves two nodes at a time. If there is a cycle in the linked list, t...
4,370
151
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\from_sequence.py
python
Python
""" Recursive Program to create a Linked List from a sequence and print a string representation of it. """ class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" ...
1,738
58
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\has_loop.py
python
Python
from __future__ import annotations from typing import Any class ContainsLoopError(Exception): pass class Node: def __init__(self, data: Any) -> None: self.data: Any = data self.next_node: Node | None = None def __iter__(self): node = self visited = set() while n...
1,764
63
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\is_palindrome.py
python
Python
from __future__ import annotations from dataclasses import dataclass @dataclass class ListNode: val: int = 0 next_node: ListNode | None = None def is_palindrome(head: ListNode | None) -> bool: """ Check if a linked list is a palindrome. Args: head: The head of the linked list. Ret...
4,818
186
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\merge_two_lists.py
python
Python
""" Algorithm that merges two sorted linked lists into one sorted linked list. """ from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: d...
2,293
84
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\middle_element_of_linked_list.py
python
Python
from __future__ import annotations class Node: def __init__(self, data: int) -> None: self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data: int) -> int: new_node = Node(new_data) new_node.next = self.hea...
1,611
69
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\print_reverse.py
python
Python
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass @dataclass class Node: data: int next_node: Node | None = None class LinkedList: """A class to represent a Linked List. Use a tail pointer to speed up the append() operation. """ ...
3,737
127
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\reverse_k_group.py
python
Python
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass @dataclass class Node: data: int next_node: Node | None = None class LinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Node | None = None for i in in...
3,194
119
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\rotate_to_the_right.py
python
Python
from __future__ import annotations from dataclasses import dataclass @dataclass class Node: data: int next_node: Node | None = None def print_linked_list(head: Node | None) -> None: """ Print the entire linked list iteratively. This function prints the elements of a linked list separat...
4,260
157
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\singly_linked_list.py
python
Python
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from typing import Any @dataclass class Node: """ Create and initialize Node class instance. >>> Node(20) Node(20) >>> Node("Hello, world!") Node(Hello, world!) >>> Node(None) Nod...
16,564
530
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\skip_list.py
python
Python
""" Based on "Skip Lists: A Probabilistic Alternative to Balanced Trees" by William Pugh https://epaperpress.com/sortsearch/download/skiplist.pdf """ from __future__ import annotations from itertools import pairwise from random import random from typing import TypeVar KT = TypeVar("KT") VT = TypeVar("VT") class No...
13,049
449
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\linked_list\swap_nodes.py
python
Python
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from typing import Any @dataclass class Node: data: Any next_node: Node | None = None @dataclass class LinkedList: head: Node | None = None def __iter__(self) -> Iterator: """ ...
4,305
149
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\queues\circular_queue.py
python
Python
# Implementation of Circular Queue (using Python lists) class CircularQueue: """Circular FIFO queue with a fixed capacity""" def __init__(self, n: int): self.n = n self.array = [None] * self.n self.front = 0 # index of the first element self.rear = 0 self.size = 0 ...
3,220
110
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\queues\circular_queue_linked_list.py
python
Python
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) ...
4,394
162
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\queues\double_ended_queue.py
python
Python
""" Implementation of double ended queue. """ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: """ Deque data structure. Operations ---------- append(val: Any) -> None appendleft(val: Any) -> None ...
14,341
464
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\queues\linked_queue.py
python
Python
"""A Queue using a linked list like structure""" from __future__ import annotations from collections.abc import Iterator from typing import Any class Node: def __init__(self, data: Any) -> None: self.data: Any = data self.next: Node | None = None def __str__(self) -> str: return f"{...
3,864
157
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\queues\priority_queue_using_list.py
python
Python
""" Pure Python implementations of a Fixed Priority Queue and an Element Priority Queue using Python lists. """ class OverFlowError(Exception): pass class UnderFlowError(Exception): pass class FixedPriorityQueue: """ Tasks can be added to a Priority Queue at any time and in any order but when Task...
5,949
233
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\queues\queue_by_list.py
python
Python
"""Queue represented by a Python list""" from collections.abc import Iterable class QueueByList[T]: def __init__(self, iterable: Iterable[T] | None = None) -> None: """ >>> QueueByList() Queue(()) >>> QueueByList([10, 20, 30]) Queue((10, 20, 30)) >>> QueueByList((i...
3,175
139
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\queues\queue_by_two_stacks.py
python
Python
"""Queue implementation using two stacks""" from collections.abc import Iterable class QueueByTwoStacks[T]: def __init__(self, iterable: Iterable[T] | None = None) -> None: """ >>> QueueByTwoStacks() Queue(()) >>> QueueByTwoStacks([10, 20, 30]) Queue((10, 20, 30)) ...
2,726
113
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\queues\queue_on_pseudo_stack.py
python
Python
"""Queue represented by a pseudo stack (represented by a list with pop and append)""" from typing import Any class Queue: def __init__(self): self.stack = [] self.length = 0 def __str__(self): printed = "<" + str(self.stack)[1:-1] + ">" return printed """Enqueues {@code ...
1,547
60
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\balanced_parentheses.py
python
Python
from .stack import Stack def balanced_parentheses(parentheses: str) -> bool: """Use a stack to check if a string of parentheses is balanced. >>> balanced_parentheses("([]{})") True >>> balanced_parentheses("[()]{}{[()()]()}") True >>> balanced_parentheses("[(])") False >>> balanced_par...
1,117
39
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\dijkstras_two_stack_algorithm.py
python
Python
""" Author: Alexander Joslin GitHub: github.com/echoaj Explanation: https://medium.com/@haleesammar/implemented-in-js-dijkstras-2-stack- algorithm-for-evaluating-mathematical-expressions-fc0837dae1ea We can use Dijkstra's two stack algorithm to solve an equation such as: (5 + ((4 * 2) * (2 + 3))) THES...
2,727
85
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\infix_to_postfix_conversion.py
python
Python
""" https://en.wikipedia.org/wiki/Infix_notation https://en.wikipedia.org/wiki/Reverse_Polish_notation https://en.wikipedia.org/wiki/Shunting-yard_algorithm """ from typing import Literal from .balanced_parentheses import balanced_parentheses from .stack import Stack PRECEDENCES: dict[str, int] = { "+": 1, "...
3,186
114
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\infix_to_prefix_conversion.py
python
Python
""" Output: Enter an Infix Equation = a + b ^c Symbol | Stack | Postfix ---------------------------- c | | c ^ | ^ | c b | ^ | cb + | + | cb^ a | + | cb^a | | cb^a+ a+b^c (Infix) -> +a^bc (Prefix) """ def infix_2_postf...
6,010
193
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\largest_rectangle_histogram.py
python
Python
def largest_rectangle_area(heights: list[int]) -> int: """ Inputs an array of integers representing the heights of bars, and returns the area of the largest rectangle that can be formed >>> largest_rectangle_area([2, 1, 5, 6, 2, 3]) 10 >>> largest_rectangle_area([2, 4]) 4 >>> largest_...
1,113
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\lexicographical_numbers.py
python
Python
from collections.abc import Iterator def lexical_order(max_number: int) -> Iterator[int]: """ Generate numbers in lexical order from 1 to max_number. >>> " ".join(map(str, lexical_order(13))) '1 10 11 12 13 2 3 4 5 6 7 8 9' >>> list(lexical_order(1)) [1] >>> " ".join(map(str, lexical_orde...
1,004
39
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\next_greater_element.py
python
Python
from __future__ import annotations arr = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] expect = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def next_greatest_element_slow(arr: list[float]) -> list[float]: """ Get the Next Greatest Element (NGE) for each element in the array b...
4,095
134
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\postfix_evaluation.py
python
Python
""" Reverse Polish Nation is also known as Polish postfix notation or simply postfix notation. https://en.wikipedia.org/wiki/Reverse_Polish_notation Classic examples of simple stack implementations. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Output: Enter a Postfix Equation ...
6,204
201
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\prefix_evaluation.py
python
Python
""" Program to evaluate a prefix expression. https://en.wikipedia.org/wiki/Polish_notation """ operators = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y, } def is_operand(c): """ Return True if the given char c is an operand, e.g. it is a...
2,078
93
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\stack.py
python
Python
from __future__ import annotations from typing import TypeVar T = TypeVar("T") class StackOverflowError(BaseException): pass class StackUnderflowError(BaseException): pass class Stack[T]: """A stack is an abstract data type that serves as a collection of elements with two principal operations: p...
4,940
216
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\stack_using_two_queues.py
python
Python
from __future__ import annotations from collections import deque from dataclasses import dataclass, field @dataclass class StackWithQueues: """ https://www.geeksforgeeks.org/implement-stack-using-queue/ >>> stack = StackWithQueues() >>> stack.push(1) >>> stack.push(2) >>> stack.push(3) >...
2,336
86
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\stack_with_doubly_linked_list.py
python
Python
# A complete working Python program to demonstrate all # stack operations using a doubly linked list from __future__ import annotations from typing import TypeVar T = TypeVar("T") class Node[T]: def __init__(self, data: T): self.data = data # Assign data self.next: Node[T] | None = None # Ini...
3,301
131
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\stack_with_singly_linked_list.py
python
Python
"""A Stack using a linked list like structure""" from __future__ import annotations from collections.abc import Iterator from typing import TypeVar T = TypeVar("T") class Node[T]: def __init__(self, data: T): self.data = data self.next: Node[T] | None = None def __str__(self) -> str: ...
3,862
166
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\stacks\stock_span_problem.py
python
Python
""" The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock's price for all n days. The span Si of the stock's price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the pri...
2,242
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\suffix_tree\example\example_usage.py
python
Python
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11554 # https://github.com/TheAlgorithms/Python/pull/11554 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! from data_structures.suffix_tree.suffix_...
1,118
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\suffix_tree\suffix_tree.py
python
Python
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11554 # https://github.com/TheAlgorithms/Python/pull/11554 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! from data_structures.suffix_tree.suffix_...
2,071
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\suffix_tree\suffix_tree_node.py
python
Python
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11554 # https://github.com/TheAlgorithms/Python/pull/11554 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! from __future__ import annotations cla...
1,342
37
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\suffix_tree\tests\test_suffix_tree.py
test
Python
# Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) # in Pull Request: #11554 # https://github.com/TheAlgorithms/Python/pull/11554 # # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request # addressing bugs/corrections to this file. # Thank you! import unittest from data_structures.su...
2,259
60
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\trie\radix_tree.py
python
Python
""" A Radix Tree is a data structure that represents a space-optimized trie (prefix tree) in whicheach node that is the only child is merged with its parent [https://en.wikipedia.org/wiki/Radix_tree] """ class RadixNode: def __init__(self, prefix: str = "", is_leaf: bool = False) -> None: # Mapping from t...
7,864
230
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
data_structures\trie\trie.py
python
Python
""" A Trie/Prefix Tree is a kind of search tree used to provide quick lookup of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup time making it an optimal approach when space is ...
3,741
128
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\change_brightness.py
python
Python
from PIL import Image def change_brightness(img: Image, level: float) -> Image: """ Change the brightness of a PIL Image to a given level. """ def brightness(c: int) -> float: """ Fundamental Transformation/Operation that'll be performed on every bit. """ retur...
777
27
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\change_contrast.py
python
Python
""" Changing contrast with PIL This algorithm is used in https://noivce.pythonanywhere.com/ Python web app. psf/black: True ruff : True """ from PIL import Image def change_contrast(img: Image, level: int) -> Image: """ Function to change contrast """ factor = (259 * (level + 255)) / (255 * (259 - ...
834
36
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\convert_to_negative.py
python
Python
""" Implemented an algorithm using opencv to convert a colored image into its negative """ from cv2 import destroyAllWindows, imread, imshow, waitKey def convert_to_negative(img): # getting number of pixels in the image pixel_h, pixel_v = img.shape[0], img.shape[1] # converting each pixel's color to its...
764
31
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\dithering\burkes.py
python
Python
""" Implementation Burke's algorithm (dithering) """ import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class Burkes: """ Burke's algorithm is using for converting grayscale image to black and white version Source: Source: https://en.wikipedia.org/wiki/Dither Note: ...
3,735
99
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\edge_detection\canny.py
python
Python
import cv2 import numpy as np from digital_image_processing.filters.convolve import img_convolve from digital_image_processing.filters.sobel_filter import sobel_filter PI = 180 def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - ce...
5,549
144
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\filters\bilateral_filter.py
python
Python
""" Implementation of Bilateral filter Inputs: img: A 2d image with values in between 0 and 1 varS: variance in space dimension. varI: variance in Intensity. N: Kernel size(Must be an odd number) Output: img:A 2d zero padded image with values in between 0 and 1 """ import math import sys import c...
2,971
89
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\filters\convolve.py
python
Python
# @Author : lightXu # @File : convolve.py # @Time : 2019/7/8 0008 下午 16:13 from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): rows, cols = image.shape dst_height = cols - block_size[1] + 1 dst_width...
1,678
50
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\filters\gabor_filter.py
python
Python
# Implementation of the Gaborfilter # https://en.wikipedia.org/wiki/Gabor_filter import numpy as np from cv2 import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filter2D, imread, imshow, waitKey def gabor_filter_kernel( ksize: int, sigma: int, theta: int, lambd: int, gamma: int, psi: int ) -> np.ndarray: """ :param...
2,705
86
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\filters\gaussian_filter.py
python
Python
""" Implementation of gaussian filter algorithm """ from itertools import product from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uint8, zeros def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = mgrid[0 - center : k_size...
1,801
54
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\filters\laplacian_filter.py
python
Python
# @Author : ojas-wani # @File : laplacian_filter.py # @Date : 10/04/2023 import numpy as np from cv2 import ( BORDER_DEFAULT, COLOR_BGR2GRAY, CV_64F, cvtColor, filter2D, imread, imshow, waitKey, ) from digital_image_processing.filters.gaussian_filter import gaussian_filter def...
2,319
82
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\filters\local_binary_pattern.py
python
Python
import cv2 import numpy as np def get_neighbors_pixel( image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int ) -> int: """ Comparing local neighborhood pixel value with threshold value of centre pixel. Exception is required when neighborhood value of a center pixel value is null. i....
3,026
81
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\filters\median_filter.py
python
Python
""" Implementation of median filter algorithm """ from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): """ :param gray_img: gray image :param mask: mask size :return: image with median ...
1,329
43