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
financial\simple_moving_average.py
python
Python
""" The Simple Moving Average (SMA) is a statistical calculation used to analyze data points by creating a constantly updated average price over a specific time period. In finance, SMA is often used in time series analysis to smooth out price data and identify trends. Reference: https://en.wikipedia.org/wiki/Moving_av...
2,363
70
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
financial\straight_line_depreciation.py
python
Python
""" In accounting, depreciation refers to the decreases in the value of a fixed asset during the asset's useful life. When an organization purchases a fixed asset, the purchase expenditure is not recognized as an expense immediately. Instead, the decreases in the asset's value are recognized as expenses over the years ...
4,022
104
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
financial\time_and_half_pay.py
python
Python
""" Calculate time and a half pay """ def pay(hours_worked: float, pay_rate: float, hours: float = 40) -> float: """ hours_worked = The total hours worked pay_rate = Amount of money per hour hours = Number of hours that must be worked before you receive time and a half >>> pay(41, 1) 41.5 ...
1,094
41
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
fractals\julia_sets.py
python
Python
"""Author Alexandre De Zotti Draws Julia sets of quadratic polynomials and exponential maps. More specifically, this iterates the function a fixed number of times then plots whether the absolute value of the last iterate is greater than a fixed threshold (named "escape radius"). For the exponential map this is not ...
6,776
218
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
fractals\koch_snowflake.py
python
Python
""" Description The Koch snowflake is a fractal curve and one of the earliest fractals to have been described. The Koch snowflake can be built up iteratively, in a sequence of stages. The first stage is an equilateral triangle, and each successive stage is formed by adding outward bends to each side of ...
4,481
116
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
fractals\mandelbrot.py
python
Python
""" The Mandelbrot set is the set of complex numbers "c" for which the series "z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a complex number "c" is a member of the Mandelbrot set if, when starting with "z_0 = 0" and applying the iteration repeatedly, the absolute value of "z_n" remains bounded...
5,276
151
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
fractals\sierpinski_triangle.py
python
Python
""" Author Anurag Kumar | anuragkumarak95@gmail.com | git/anuragkumarak95 Simple example of fractal generation using recursion. What is the Sierpiński Triangle? The Sierpiński triangle (sometimes spelled Sierpinski), also called the Sierpiński gasket or Sierpiński sieve, is a fractal attractive fixed set with the...
2,833
87
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
fractals\vicsek.py
python
Python
"""Authors Bastien Capiaux & Mehdi Oudghiri The Vicsek fractal algorithm is a recursive algorithm that creates a pattern known as the Vicsek fractal or the Vicsek square. It is based on the concept of self-similarity, where the pattern at each level of recursion resembles the overall pattern. The algorithm involves di...
2,306
77
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
fuzzy_logic\fuzzy_operations.py
python
Python
""" By @Shreya123714 https://en.wikipedia.org/wiki/Fuzzy_set """ from __future__ import annotations from dataclasses import dataclass import matplotlib.pyplot as plt import numpy as np @dataclass class FuzzySet: """ A class for representing and manipulating triangular fuzzy sets. Attributes: n...
6,209
196
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
genetic_algorithm\basic_string.py
python
Python
""" Simple multithreaded algorithm to show how the 4 phases of a genetic algorithm works (Evaluation, Selection, Crossover and Mutation) https://en.wikipedia.org/wiki/Genetic_algorithm Author: D4rkia """ from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is...
8,271
209
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
geodesy\haversine_distance.py
python
Python
from math import asin, atan, cos, radians, sin, sqrt, tan AXIS_A = 6378137.0 AXIS_B = 6356752.314245 RADIUS = 6378137 def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """ Calculate great circle distance between two points in a sphere, given longitudes and latitudes htt...
2,459
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
geodesy\lamberts_ellipsoidal_distance.py
python
Python
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance AXIS_A = 6378137.0 AXIS_B = 6356752.314245 EQUATORIAL_RADIUS = 6378137 def lamberts_ellipsoidal_distance( lat1: float, lon1: float, lat2: float, lon2: float ) -> float: """ Calculate the shortest distance al...
4,557
114
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
geometry\geometry.py
python
Python
from __future__ import annotations import math from dataclasses import dataclass, field from types import NoneType from typing import Self # Building block classes @dataclass class Angle: """ An Angle in degrees (unit of measurement) >>> Angle() Angle(degrees=90) >>> Angle(45.5) Angle(degre...
8,392
289
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
geometry\graham_scan.py
python
Python
""" Graham Scan algorithm for finding the convex hull of a set of points. The Graham scan is a method of computing the convex hull of a finite set of points in the plane with time complexity O(n log n). It is named after Ronald Graham, who published the original algorithm in 1972. The algorithm finds all vertices of ...
7,891
247
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
geometry\jarvis_march.py
python
Python
""" Jarvis March (Gift Wrapping) algorithm for finding the convex hull of a set of points. The convex hull is the smallest convex polygon that contains all the points. Time Complexity: O(n*h) where n is the number of points and h is the number of hull points. Space Complexity: O(h) where h is the number of hull point...
6,053
188
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
geometry\tests\test_graham_scan.py
test
Python
""" Tests for the Graham scan convex hull algorithm. """ from geometry.graham_scan import Point, graham_scan def test_empty_points() -> None: """Test with no points.""" assert graham_scan([]) == [] def test_single_point() -> None: """Test with a single point.""" assert graham_scan([Point(0, 0)]) ==...
7,138
267
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
geometry\tests\test_jarvis_march.py
test
Python
""" Unit tests for Jarvis March (Gift Wrapping) algorithm. """ from geometry.jarvis_march import Point, jarvis_march class TestPoint: """Tests for the Point class.""" def test_point_creation(self) -> None: """Test Point initialization.""" p = Point(1.0, 2.0) assert p.x == 1.0 ...
3,762
116
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphics\bezier_curve.py
python
Python
# https://en.wikipedia.org/wiki/B%C3%A9zier_curve # https://www.tutorialspoint.com/computer_graphics/computer_graphics_curves.htm from __future__ import annotations from scipy.special import comb class BezierCurve: """ Bezier curve is a weighted sum of a set of control points. Generate Bezier curves from...
4,392
115
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphics\butterfly_pattern.py
python
Python
def butterfly_pattern(n: int) -> str: """ Creates a butterfly pattern of size n and returns it as a string. >>> print(butterfly_pattern(3)) * * ** ** ***** ** ** * * >>> print(butterfly_pattern(5)) * * ** ** *** *** **** **** ********* **** **...
1,056
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphics\digital_differential_analyzer_line.py
python
Python
import matplotlib.pyplot as plt def digital_differential_analyzer_line( p1: tuple[int, int], p2: tuple[int, int] ) -> list[tuple[int, int]]: """ Draws a line between two points using the DDA algorithm. Args: - p1: Coordinates of the starting point. - p2: Coordinates of the ending point. R...
1,566
53
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphics\vector3_for_2d_rendering.py
python
Python
""" render 3d points for 2d surfaces. """ from __future__ import annotations import math __version__ = "2020.9.26" __author__ = "xcodz-dot, cclaus, dhruvmanila" def convert_to_2d( x: float, y: float, z: float, scale: float, distance: float ) -> tuple[float, float]: """ Converts 3d point to a 2d drawabl...
3,364
103
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\a_star.py
python
Python
from __future__ import annotations DIRECTIONS = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] # function to search the path def search( grid: list[list[int]], init: list[int], goal: list[int], cost: int, heuristic: list[list[int]], ) -> tuple[list[list[int]]...
4,687
139
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\ant_colony_optimization_algorithms.py
python
Python
""" Use an ant colony optimization algorithm to solve the travelling salesman problem (TSP) which asks the following question: "Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?" https://en.wiki...
8,371
225
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\articulation_points.py
python
Python
# Finding Articulation Points in Undirected Graph def compute_ap(graph): n = len(graph) out_edge_count = 0 low = [0] * n visited = [False] * n is_art = [False] * n def dfs(root, at, parent, out_edge_count): if parent == root: out_edge_count += 1 visited[at] = True ...
1,401
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\basic_graphs.py
python
Python
from collections import deque def _input(message): return input(message).strip().split(" ") def initialize_unweighted_directed_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range...
11,124
410
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\bellman_ford.py
python
Python
from __future__ import annotations def print_distance(distance: list[float], src): print(f"Vertex\tShortest Distance from vertex {src}") for i, d in enumerate(distance): print(f"{i}\t\t{d}") def check_negative_cycle( graph: list[dict[str, int]], distance: list[float], edge_count: int ): for ...
2,377
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\bi_directional_dijkstra.py
python
Python
""" Bi-directional Dijkstra's algorithm. A bi-directional approach is an efficient and less time consuming optimization for Dijkstra's searching algorithm Reference: shorturl.at/exHM7 """ # Author: Swayam Singh (https://github.com/practice404) from queue import PriorityQueue from typing import Any import numpy as ...
3,501
141
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\bidirectional_a_star.py
python
Python
""" https://en.wikipedia.org/wiki/Bidirectional_search """ from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean HEURISTIC = 0 grid = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], ...
8,463
260
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\bidirectional_breadth_first_search.py
python
Python
""" https://en.wikipedia.org/wiki/Bidirectional_search """ from __future__ import annotations import time Path = list[tuple[int, int]] grid = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0,...
6,233
189
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\bidirectional_search.py
python
Python
""" Bidirectional Search Algorithm. This algorithm searches from both the source and target nodes simultaneously, meeting somewhere in the middle. This approach can significantly reduce the search space compared to a traditional one-directional search. Time Complexity: O(b^(d/2)) where b is the branching factor and d...
5,857
202
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\boruvka.py
python
Python
"""Borůvka's algorithm. Determines the minimum spanning tree (MST) of a graph using the Borůvka's algorithm. Borůvka's algorithm is a greedy algorithm for finding a minimum spanning tree in a connected graph, or a minimum spanning forest if a graph that is not connected. The time complexity of this algorithm is O(ELo...
6,587
177
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\breadth_first_search.py
python
Python
#!/usr/bin/python """Author: OMKAR PATHAK""" from __future__ import annotations from queue import Queue class Graph: def __init__(self) -> None: self.vertices: dict[int, list[int]] = {} def print_graph(self) -> None: """ prints adjacency list representation of graaph >>> g ...
2,483
94
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\breadth_first_search_2.py
python
Python
""" https://en.wikipedia.org/wiki/Breadth-first_search pseudo-code: breadth_first_search(graph G, start vertex s): // all nodes initially unexplored mark s as explored let Q = queue data structure, initialized with s while Q is non-empty: remove the first node of Q, call it v for each edge(v, w): // for w in g...
2,408
89
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\breadth_first_search_shortest_path.py
python
Python
"""Breath First Search (BFS) can be used when finding the shortest path from a given source node to a target node in an unweighted graph. """ from __future__ import annotations graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["...
3,110
91
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\breadth_first_search_shortest_path_2.py
python
Python
"""Breadth-first search the shortest path implementations. doctest: python -m doctest -v breadth_first_search_shortest_path_2.py Manual test: python breadth_first_search_shortest_path_2.py """ from collections import deque demo_graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], ...
3,712
114
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\breadth_first_search_zero_one_shortest_path.py
python
Python
""" Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra. 0-1-graph is the weighted graph with the weights equal to 0 or 1. Link: https://codeforces.com/blog/entry/22276 """ from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclass...
4,803
144
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\check_bipatrite.py
python
Python
from collections import defaultdict, deque def is_bipartite_dfs(graph: dict[int, list[int]]) -> bool: """ Check if a graph is bipartite using depth-first search (DFS). Args: `graph`: Adjacency list representing the graph. Returns: ``True`` if bipartite, ``False`` otherwise. Chec...
5,591
162
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\check_cycle.py
python
Python
""" Program to check if a cycle is present in a given graph """ def check_cycle(graph: dict) -> bool: """ Returns True if graph is cyclic else False >>> check_cycle(graph={0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]}) False >>> check_cycle(graph={0:[1, 2], 1:[2], 2:[0, 3], 3:[3]}) True ""...
1,590
53
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\connected_components.py
python
Python
""" https://en.wikipedia.org/wiki/Component_(graph_theory) Finding connected components in graph """ test_graph_1 = {0: [1, 2], 1: [0, 3], 2: [0], 3: [1], 4: [5, 6], 5: [4, 6], 6: [4, 5]} test_graph_2 = {0: [1, 2, 3], 1: [0, 3], 2: [0], 3: [0, 1], 4: [], 5: []} def dfs(graph: dict, vert: int, visited: list) -> li...
1,488
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\deep_clone_graph.py
python
Python
""" LeetCode 133. Clone Graph https://leetcode.com/problems/clone-graph/ Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. """ from dataclasses import dataclass @dataclass cl...
1,819
79
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\depth_first_search.py
python
Python
"""Non recursive implementation of a DFS algorithm.""" from __future__ import annotations def depth_first_search(graph: dict, start: str) -> set[str]: """Depth First Search on Graph :param graph: directed graph in dictionary format :param start: starting vertex as a string :returns: the trace of the ...
1,440
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\depth_first_search_2.py
python
Python
#!/usr/bin/python """Author: OMKAR PATHAK""" class Graph: def __init__(self): self.vertex = {} # for printing the Graph vertices def print_graph(self) -> None: """ Print the graph vertices. Example: >>> g = Graph() >>> g.add_edge(0, 1) >>> g.add_e...
3,446
128
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\dijkstra.py
python
Python
""" pseudo-code DIJKSTRA(graph G, start vertex s, destination vertex d): //all nodes initially unexplored 1 - let H = min heap data structure, initialized with 0 and s [here 0 indicates the distance from start vertex s] 2 - while H is non-empty: 3 - remove the first node and cost of H, call it U and cost 4...
3,335
120
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\dijkstra_2.py
python
Python
def print_dist(dist, v): print("\nVertex Distance") for i in range(v): if dist[i] != float("inf"): print(i, "\t", int(dist[i]), end="\t") else: print(i, "\t", "INF", end="\t") print() def min_dist(mdist, vset, v): min_val = float("inf") min_ind = -1 ...
1,608
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\dijkstra_algorithm.py
python
Python
# Title: Dijkstra's Algorithm for finding single source shortest path from scratch # Author: Shubham Malik # References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm import math import sys # For storing the vertex set to retrieve node with the lowest distance class PriorityQueue: # Based on Min Heap ...
15,131
485
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\dijkstra_alternate.py
python
Python
from __future__ import annotations class Graph: def __init__(self, vertices: int) -> None: """ >>> graph = Graph(2) >>> graph.vertices 2 >>> len(graph.graph) 2 >>> len(graph.graph[0]) 2 """ self.vertices = vertices self.graph ...
3,296
99
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\dijkstra_binary_grid.py
python
Python
""" This script implements the Dijkstra algorithm on a binary grid. The grid consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. Diagonal movement can be allowed or disallowed. """ from heapq import heapp...
2,964
90
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\dinic.py
python
Python
INF = float("inf") class Dinic: def __init__(self, n): self.lvl = [0] * n self.ptr = [0] * n self.q = [0] * n self.adj = [[] for _ in range(n)] """ Here we will add our edges containing with the following parameters: vertex closest to source, vertex closest to sink and...
3,151
95
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\directed_and_undirected_weighted_graph.py
python
Python
from collections import deque from math import floor from random import random from time import time # the default weight is 1 if not assigned but all the implementation is weighted class DirectedGraph: def __init__(self): self.graph = {} # adding vertices and edges # adding the weight is option...
16,071
490
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\edmonds_karp_multiple_source_and_sink.py
python
Python
class FlowNetwork: def __init__(self, graph, sources, sinks): self.source_index = None self.sink_index = None self.graph = graph self._normalize_graph(sources, sinks) self.vertices_count = len(graph) self.maximum_flow_algorithm = None # make only one source and ...
6,785
194
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\eulerian_path_and_circuit_for_undirected_graph.py
python
Python
# Eulerian Path is a path in graph that visits every edge exactly once. # Eulerian Circuit is an Eulerian Path which starts and ends on the same # vertex. # time complexity is O(V+E) # space complexity is O(VE) # using dfs for finding eulerian path traversal def dfs(u, graph, visited_edge, path=None): path = (pat...
2,112
72
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\even_tree.py
python
Python
""" You are given a tree(a simple connected graph with no cycles). The tree has N nodes numbered from 1 to N and is rooted at node 1. Find the maximum number of edges you can remove from the tree to get a forest such that each connected component of the forest contains an even number of nodes. Constraints 2 <= 2 <= 1...
1,395
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\finding_bridges.py
python
Python
""" An edge is a bridge if, after removing it count of connected components in graph will be increased by one. Bridges represent vulnerabilities in a connected network and are useful for designing reliable networks. For example, in a wired computer network, an articulation point indicates the critical computers and a b...
2,873
107
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\frequent_pattern_graph_miner.py
python
Python
""" FP-GraphMiner - A Fast Frequent Pattern Mining Algorithm for Network Graphs A novel Frequent Pattern Graph Mining algorithm, FP-GraphMiner, that compactly represents a set of network graphs as a Frequent Pattern Graph (or FP-Graph). This graph can be used to efficiently mine frequent subgraphs including maximal fr...
7,355
234
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\g_topological_sort.py
python
Python
# Author: Phyllipe Bezerra (https://github.com/pmba) clothes = { 0: "underwear", 1: "pants", 2: "belt", 3: "suit", 4: "shoe", 5: "socks", 6: "shirt", 7: "tie", 8: "watch", } graph = [[1, 4], [2, 4], [3], [], [], [4], [2, 7], [3], []] visited = [0 for x in range(len(graph))] stack ...
993
48
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\gale_shapley_bigraph.py
python
Python
from __future__ import annotations def stable_matching( donor_pref: list[list[int]], recipient_pref: list[list[int]] ) -> list[int]: """ Finds the stable match in any bipartite graph, i.e a pairing where no 2 objects prefer each other over their partner. The function accepts the preferences of oe...
2,040
50
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\graph_adjacency_list.py
python
Python
#!/usr/bin/env python3 """ Author: Vikram Nithyanandam Description: The following implementation is a robust unweighted Graph data structure implemented using an adjacency list. This vertices and edges of this graph can be effectively initialized and modified while storing your chosen generic value in each vertex. Ad...
22,281
598
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\graph_adjacency_matrix.py
python
Python
#!/usr/bin/env python3 """ Author: Vikram Nithyanandam Description: The following implementation is a robust unweighted Graph data structure implemented using an adjacency matrix. This vertices and edges of this graph can be effectively initialized and modified while storing your chosen generic value in each vertex. ...
22,723
610
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\graph_list.py
python
Python
#!/usr/bin/env python3 # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import TypeVar T = TypeVar("T") class GraphAdjacencyList[T]: """ Adjacency List type Graph Data Structure that acc...
6,700
151
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\graphs_floyd_warshall.py
python
Python
# floyd_warshall.py """ The problem is to find the shortest distance between all pairs of vertices in a weighted directed graph that can have negative edge weights. """ def _print_dist(dist, v): print("\nThe shortest path matrix using Floyd Warshall algorithm\n") for i in range(v): for j in range(v): ...
3,312
103
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\greedy_best_first.py
python
Python
""" https://en.wikipedia.org/wiki/Best-first_search#Greedy_BFS """ from __future__ import annotations Path = list[tuple[int, int]] # 0's are free path whereas 1's are obstacles TEST_GRIDS = [ [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0,...
5,588
200
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\greedy_min_vertex_cover.py
python
Python
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Approximization algorithm for minimum vertex cover problem. Greedy Approach. Uses graphs represented with an adjacency list URL: https://mathworld.wolfram.com/MinimumVertexCover.html URL: https://cs.stackexchange.com/question...
2,396
65
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\kahns_algorithm_long.py
python
Python
# Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm def longest_distance(graph): indegree = [0] * len(graph) queue = [] long_dist = [1] * len(graph) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if i...
802
31
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\kahns_algorithm_topo.py
python
Python
def topological_sort(graph: dict[int, list[int]]) -> list[int] | None: """ Perform topological sorting of a Directed Acyclic Graph (DAG) using Kahn's Algorithm via Breadth-First Search (BFS). Topological sorting is a linear ordering of vertices in a graph such that for every directed edge u → v, ve...
1,896
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\karger.py
python
Python
""" An implementation of Karger's Algorithm for partitioning a graph. """ from __future__ import annotations import random # Adjacency list representation of this graph: # https://en.wikipedia.org/wiki/File:Single_run_of_Karger%E2%80%99s_Mincut_algorithm.svg TEST_GRAPH = { "1": ["2", "3", "4", "5"], "2": ["1...
2,659
86
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\lanczos_eigenvectors.py
python
Python
""" Lanczos Method for Finding Eigenvalues and Eigenvectors of a Graph. This module demonstrates the Lanczos method to approximate the largest eigenvalues and corresponding eigenvectors of a symmetric matrix represented as a graph's adjacency list. The method efficiently handles large, sparse matrices by converting th...
8,050
207
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\markov_chain.py
python
Python
from __future__ import annotations from collections import Counter from random import random class MarkovChainGraphUndirectedUnweighted: """ Undirected Unweighted Graph for running Markov Chain Algorithm """ def __init__(self): self.connections = {} def add_node(self, node: str) -> None...
2,169
85
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\matching_min_vertex_cover.py
python
Python
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Approximization algorithm for minimum vertex cover problem. Matching Approach. Uses graphs represented with an adjacency list URL: https://mathworld.wolfram.com/MinimumVertexCover.html URL: https://www.princeton.edu/~aaa/Pub...
2,243
63
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\minimum_path_sum.py
python
Python
def min_path_sum(grid: list) -> int: """ Find the path from top left to bottom right of array of numbers with the lowest possible sum and return the sum along this path. >>> min_path_sum([ ... [1, 3, 1], ... [1, 5, 1], ... [4, 2, 1], ... ]) 7 >>> min_path_sum([ ....
1,643
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\minimum_spanning_tree_boruvka.py
python
Python
class Graph: """ Data structure to store graphs (based on adjacency lists) """ def __init__(self): self.num_vertices = 0 self.num_edges = 0 self.adjacency = {} def add_vertex(self, vertex): """ Adds a vertex to the graph """ if vertex not in...
5,930
197
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\minimum_spanning_tree_kruskal.py
python
Python
def kruskal( num_nodes: int, edges: list[tuple[int, int, int]] ) -> list[tuple[int, int, int]]: """ >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1)]) [(2, 3, 1), (0, 1, 3), (1, 2, 5)] >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2)]) [(2, 3, 1), (0, 2, 1), (0, 1, 3)] ...
1,399
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\minimum_spanning_tree_kruskal2.py
python
Python
from __future__ import annotations from typing import TypeVar T = TypeVar("T") class DisjointSetTreeNode[T]: # Disjoint Set Node to store the parent and rank def __init__(self, data: T) -> None: self.data = data self.parent = self self.rank = 0 class DisjointSetTree[T]: # Disjo...
4,180
122
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\minimum_spanning_tree_prims.py
python
Python
import sys from collections import defaultdict class Heap: def __init__(self): self.node_position = [] def get_position(self, vertex): return self.node_position[vertex] def set_position(self, vertex, pos): self.node_position[vertex] = pos def top_to_bottom(self, heap, start,...
5,019
136
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\minimum_spanning_tree_prims2.py
python
Python
""" Prim's (also known as Jarník's) algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. The algorithm operates by buil...
9,220
270
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\multi_heuristic_astar.py
python
Python
import heapq import sys import numpy as np TPos = tuple[int, int] class PriorityQueue: def __init__(self): self.elements = [] self.set = set() def minkey(self): if not self.empty(): return self.elements[0][0] else: return float("inf") def empty(s...
8,876
313
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\page_rank.py
python
Python
""" Author: https://github.com/bhushan-borole """ """ The input graph for the algorithm is: A B C A 0 1 1 B 0 0 1 C 1 0 0 """ graph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]] class Node: def __init__(self, name): self.name = name self.inbound = [] self.outbound = [] def add_inbound(sel...
1,549
72
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\prim.py
python
Python
"""Prim's Algorithm. Determines the minimum spanning tree(MST) of a graph using the Prim's Algorithm. Details: https://en.wikipedia.org/wiki/Prim%27s_algorithm """ import heapq as hq import math from collections.abc import Iterator class Vertex: """Class Vertex.""" def __init__(self, id_): """ ...
3,658
153
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\random_graph_generator.py
python
Python
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Random graphs generator. Uses graphs represented with an adjacency list. URL: https://en.wikipedia.org/wiki/Random_graph """ import random def random_graph( vertices_number: int, probability: float, directed: bool = F...
2,231
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\scc_kosaraju.py
python
Python
from __future__ import annotations def dfs(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True for v in graph[u]: dfs(v) stack.append(u) def dfs2(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: ...
1,344
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\strongly_connected_components.py
python
Python
""" https://en.wikipedia.org/wiki/Strongly_connected_component Finding strongly connected components in directed graph """ test_graph_1 = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} test_graph_2 = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def topology_sort( graph: dict[int, list[int]], vert: int, ...
2,589
91
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\tarjans_scc.py
python
Python
from collections import deque def tarjan(g: list[list[int]]) -> list[list[int]]: """ Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachabl...
3,684
107
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\tests\test_min_spanning_tree_kruskal.py
test
Python
from graphs.minimum_spanning_tree_kruskal import kruskal def test_kruskal_successful_result(): num_nodes = 9 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], ...
703
37
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
graphs\tests\test_min_spanning_tree_prim.py
test
Python
from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def test_prim_successful_result(): num_nodes, num_edges = 9, 14 # noqa: F841 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], ...
1,047
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
greedy_methods\best_time_to_buy_and_sell_stock.py
python
Python
""" Given a list of stock prices calculate the maximum profit that can be made from a single buy and sell of one share of stock. We only allowed to complete one buy transaction and one sell transaction but must buy before we sell. Example : prices = [7, 1, 5, 3, 6, 4] max_profit will return 5 - which is by buying at ...
1,294
43
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
greedy_methods\fractional_cover_problem.py
python
Python
# https://en.wikipedia.org/wiki/Set_cover_problem from dataclasses import dataclass from operator import attrgetter @dataclass class Item: weight: int value: int @property def ratio(self) -> float: """ Return the value-to-weight ratio for the item. Returns: float...
2,640
103
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
greedy_methods\fractional_knapsack.py
python
Python
from bisect import bisect from itertools import accumulate def frac_knapsack(vl, wt, w, n): """ >>> frac_knapsack([60, 100, 120], [10, 20, 30], 50, 3) 240.0 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 10, 4) 105.0 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, 4) 95.0 >>> f...
1,482
52
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
greedy_methods\fractional_knapsack_2.py
python
Python
# https://en.wikipedia.org/wiki/Continuous_knapsack_problem # https://www.guru99.com/fractional-knapsack-problem-greedy.html # https://medium.com/walkinthecode/greedy-algorithm-fractional-knapsack-problem-9aba1daecc93 from __future__ import annotations def fractional_knapsack( value: list[int], weight: list[int]...
1,708
54
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
greedy_methods\gas_station.py
python
Python
""" Task: There are n gas stations along a circular route, where the amount of gas at the ith station is gas_quantities[i]. You have a car with an unlimited gas tank and it costs costs[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas sta...
3,058
99
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
greedy_methods\minimum_coin_change.py
python
Python
""" Test cases: Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make in Indian Currency: 987 Following is minimal change for 987 : 500 100 100 100 100 50 20 10 5 2 Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:10 1 5 10 20 50 100 200 500 1000 2000 Ente...
3,160
101
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
greedy_methods\minimum_waiting_time.py
python
Python
""" Calculate the minimum waiting time using a greedy algorithm. reference: https://www.youtube.com/watch?v=Sf3eiO12eJs For doctests run following command: python -m doctest -v minimum_waiting_time.py The minimum_waiting_time function uses a greedy algorithm to calculate the minimum time for queries to complete. It s...
1,447
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
greedy_methods\optimal_merge_pattern.py
python
Python
""" This is a pure Python implementation of the greedy-merge-sort algorithm reference: https://www.geeksforgeeks.org/optimal-file-merge-patterns/ For doctests run following command: python3 -m doctest -v greedy_merge_sort.py Objective Merge a set of sorted files of different length into a single sorted file. We need ...
1,693
57
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
greedy_methods\smallest_range.py
python
Python
""" smallest_range function takes a list of sorted integer lists and finds the smallest range that includes at least one number from each list, using a min heap for efficiency. """ from heapq import heappop, heappush from sys import maxsize def smallest_range(nums: list[list[int]]) -> list[int]: """ Find the...
2,225
73
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\adler32.py
python
Python
""" Adler-32 is a checksum algorithm which was invented by Mark Adler in 1995. Compared to a cyclic redundancy check of the same length, it trades reliability for speed (preferring the latter). Adler-32 is more reliable than Fletcher-16, and slightly less reliable than Fletcher-32.[2] source: https://en.wikipedia.org/...
789
31
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\chaos_machine.py
python
Python
"""example of simple chaos machine""" # Chaos Machine (K, t, m) K = [0.33, 0.44, 0.55, 0.44, 0.33] t = 3 m = 5 # Buffer Space (with Parameters Space) buffer_space: list[float] = [] params_space: list[float] = [] # Machine Time machine_time = 0 def push(seed): global buffer_space, params_space, machine_time, K,...
2,522
103
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\djb2.py
python
Python
""" This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c Another version of this algorithm (now favored by Bernstein) uses xor: hash(i) = hash(i - 1) * 33 ^ str[i]; First Magic constant 33: It has never been adequately explained. It's magic because it works better tha...
936
36
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\elf.py
python
Python
def elf_hash(data: str) -> int: """ Implementation of ElfHash Algorithm, a variant of PJW hash function. >>> elf_hash('lorem ipsum') 253956621 """ hash_ = x = 0 for letter in data: hash_ = (hash_ << 4) + ord(letter) x = hash_ & 0xF0000000 if x != 0: hash_...
461
22
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\enigma_machine.py
python
Python
alphabets = [chr(i) for i in range(32, 126)] gear_one = list(range(len(alphabets))) gear_two = list(range(len(alphabets))) gear_three = list(range(len(alphabets))) reflector = list(reversed(range(len(alphabets)))) code = [] gear_one_pos = gear_two_pos = gear_three_pos = 0 def rotator(): global gear_one_pos gl...
1,725
60
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\fletcher16.py
python
Python
""" The Fletcher checksum is an algorithm for computing a position-dependent checksum devised by John G. Fletcher (1934-2012) at Lawrence Livermore Labs in the late 1970s.[1] The objective of the Fletcher checksum was to provide error-detection properties approaching those of a cyclic redundancy check but with the lowe...
1,046
37
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\hamming_code.py
python
Python
# Author: João Gustavo A. Amorim & Gabriel Kunz # Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-...
9,536
287
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
hashes\luhn.py
python
Python
"""Luhn Algorithm""" from __future__ import annotations def is_luhn(string: str) -> bool: """ Perform Luhn validation on an input string Algorithm: * Double every other digit starting from 2nd last digit. * Subtract 9 if number is greater than 9. * Sum the numbers * >>> test_cases = (...
1,275
44