repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/recursive_quick_sort.py
sorts/recursive_quick_sort.py
def quick_sort(data: list) -> list: """ >>> for data in ([2, 1, 0], [2.2, 1.1, 0], "quick_sort"): ... quick_sort(data) == sorted(data) True True True """ if len(data) <= 1: return data else: return [ *quick_sort([e for e in data[1:] if e <= data[0]]), ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/bubble_sort.py
sorts/bubble_sort.py
from typing import Any def bubble_sort_iterative(collection: list[Any]) -> list[Any]: """Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/shrink_shell_sort.py
sorts/shrink_shell_sort.py
""" This function implements the shell sort algorithm which is slightly faster than its pure implementation. This shell sort is implemented using a gap, which shrinks by a certain factor each iteration. In this implementation, the gap is initially set to the length of the collection. The gap is then reduced by a certa...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/merge_insertion_sort.py
sorts/merge_insertion_sort.py
""" This is a pure Python implementation of the merge-insertion sort algorithm Source: https://en.wikipedia.org/wiki/Merge-insertion_sort For doctests run following command: python3 -m doctest -v merge_insertion_sort.py or python -m doctest -v merge_insertion_sort.py For manual testing run: python3 merge_insertion_so...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/msd_radix_sort.py
sorts/msd_radix_sort.py
""" Python implementation of the MSD radix sort algorithm. It used the binary representation of the integers to sort them. https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations def msd_radix_sort(list_of_ints: list[int]) -> list[int]: """ Implementation of the MSD radix sort algorit...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/gnome_sort.py
sorts/gnome_sort.py
""" Gnome Sort Algorithm (A.K.A. Stupid Sort) This algorithm iterates over a list comparing an element with the previous one. If order is not respected, it swaps element backward until order is respected with previous element. It resumes the initial iteration from element new position. For doctests run following com...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/sorts/cocktail_shaker_sort.py
sorts/cocktail_shaker_sort.py
""" An implementation of the cocktail shaker sort algorithm in pure Python. https://en.wikipedia.org/wiki/Cocktail_shaker_sort """ def cocktail_shaker_sort(arr: list[int]) -> list[int]: """ Sorts a list using the Cocktail Shaker Sort algorithm. :param arr: List of elements to be sorted. :return: Sor...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/computer_vision/cnn_classification.py
computer_vision/cnn_classification.py
""" Convolutional Neural Network Objective : To train a CNN model detect if TB is present in Lung X-ray or not. Resources CNN Theory : https://en.wikipedia.org/wiki/Convolutional_neural_network Resources Tensorflow : https://www.tensorflow.org/tutorials/images/cnn Download dataset from : https://lhncbc.nlm.nih.g...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/computer_vision/intensity_based_segmentation.py
computer_vision/intensity_based_segmentation.py
# Source: "https://www.ijcse.com/docs/IJCSE11-02-03-117.pdf" # Importing necessary libraries import matplotlib.pyplot as plt import numpy as np from PIL import Image def segment_image(image: np.ndarray, thresholds: list[int]) -> np.ndarray: """ Performs image segmentation based on intensity thresholds. ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/computer_vision/flip_augmentation.py
computer_vision/flip_augmentation.py
import glob import os import random from string import ascii_lowercase, digits import cv2 """ Flip image and bounding box for computer vision task https://paperswithcode.com/method/randomhorizontalflip """ # Params LABEL_DIR = "" IMAGE_DIR = "" OUTPUT_DIR = "" FLIP_TYPE = 1 # (0 is vertical, 1 is horizontal) def ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/computer_vision/harris_corner.py
computer_vision/harris_corner.py
import cv2 import numpy as np """ Harris Corner Detector https://en.wikipedia.org/wiki/Harris_Corner_Detector """ class HarrisCorner: def __init__(self, k: float, window_size: int): """ k : is an empirically determined constant in [0.04,0.06] window_size : neighbourhoods considered ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/computer_vision/mean_threshold.py
computer_vision/mean_threshold.py
from PIL import Image """ Mean thresholding algorithm for image processing https://en.wikipedia.org/wiki/Thresholding_(image_processing) """ def mean_threshold(image: Image) -> Image: """ image: is a grayscale PIL image object """ height, width = image.size mean = 0 pixels = image.load() ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/computer_vision/__init__.py
computer_vision/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/computer_vision/haralick_descriptors.py
computer_vision/haralick_descriptors.py
""" https://en.wikipedia.org/wiki/Image_texture https://en.wikipedia.org/wiki/Co-occurrence_matrix#Application_to_image_analysis """ import imageio.v2 as imageio import numpy as np def root_mean_square_error(original: np.ndarray, reference: np.ndarray) -> float: """Simple implementation of Root Mean Squared Erro...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/computer_vision/horn_schunck.py
computer_vision/horn_schunck.py
""" The Horn-Schunck method estimates the optical flow for every single pixel of a sequence of images. It works by assuming brightness constancy between two consecutive frames and smoothness in the optical flow. Useful resources: Wikipedia: https://en.wikipedia.org/wiki/Horn%E2%80%93Schunck_method Paper: http://image....
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/computer_vision/mosaic_augmentation.py
computer_vision/mosaic_augmentation.py
"""Source: https://github.com/jason9075/opencv-mosaic-data-aug""" import glob import os import random from string import ascii_lowercase, digits import cv2 import numpy as np # Parameters OUTPUT_SIZE = (720, 1280) # Height, Width SCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it. FILTER_...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/computer_vision/pooling_functions.py
computer_vision/pooling_functions.py
# Source : https://computersciencewiki.org/index.php/Max-pooling_/_Pooling # Importing the libraries import numpy as np from PIL import Image # Maxpooling Function def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform maxpooling on the input array of 2D ma...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/networking_flow/ford_fulkerson.py
networking_flow/ford_fulkerson.py
""" Ford-Fulkerson Algorithm for Maximum Flow Problem * https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm Description: (1) Start with initial flow as 0 (2) Choose the augmenting path from source to sink and add the path to flow """ graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/networking_flow/minimum_cut.py
networking_flow/minimum_cut.py
# Minimum cut on Ford_Fulkerson algorithm. test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def bfs(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [Fals...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/networking_flow/__init__.py
networking_flow/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/or_gate.py
boolean_algebra/or_gate.py
""" An OR Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 0, and 1 (True) otherwise. Following is the truth table of an AND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/xor_gate.py
boolean_algebra/xor_gate.py
""" A XOR Gate is a logic gate in boolean algebra which results to 1 (True) if only one of the two inputs is 1, and 0 (False) if an even number of inputs are 1. Following is the truth table of a XOR Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/xnor_gate.py
boolean_algebra/xnor_gate.py
""" A XNOR Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are different, and 1 (True), if the inputs are same. It's similar to adding a NOT gate to an XOR gate Following is the truth table of a XNOR Gate: ------------------------------ | Input 1 | Input 2 | Output | -...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/karnaugh_map_simplification.py
boolean_algebra/karnaugh_map_simplification.py
""" https://en.wikipedia.org/wiki/Karnaugh_map https://www.allaboutcircuits.com/technical-articles/karnaugh-map-boolean-algebraic-simplification-technique """ def simplify_kmap(kmap: list[list[int]]) -> str: """ Simplify the Karnaugh map. >>> simplify_kmap(kmap=[[0, 1], [1, 1]]) "A'B + AB' + AB" >...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/imply_gate.py
boolean_algebra/imply_gate.py
""" An IMPLY Gate is a logic gate in boolean algebra which results to 1 if either input 1 is 0, or if input 1 is 1, then the output is 1 only if input 2 is 1. It is true if input 1 implies input 2. Following is the truth table of an IMPLY Gate: ------------------------------ | Input 1 | Input 2 | Output | ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/quine_mc_cluskey.py
boolean_algebra/quine_mc_cluskey.py
from __future__ import annotations from collections.abc import Sequence from typing import Literal def compare_string(string1: str, string2: str) -> str | Literal[False]: """ >>> compare_string('0010','0110') '0_10' >>> compare_string('0110','1101') False """ list1 = list(string1) li...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/and_gate.py
boolean_algebra/and_gate.py
""" An AND Gate is a logic gate in boolean algebra which results to 1 (True) if all the inputs are 1 (True), and 0 (False) otherwise. Following is the truth table of a Two Input AND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/nimply_gate.py
boolean_algebra/nimply_gate.py
""" An NIMPLY Gate is a logic gate in boolean algebra which results to 0 if either input 1 is 0, or if input 1 is 1, then it is 0 only if input 2 is 1. It is false if input 1 implies input 2. It is the negated form of imply Following is the truth table of an NIMPLY Gate: ------------------------------ | Input ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/__init__.py
boolean_algebra/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/not_gate.py
boolean_algebra/not_gate.py
""" A NOT Gate is a logic gate in boolean algebra which results to 0 (False) if the input is high, and 1 (True) if the input is low. Following is the truth table of a XOR Gate: ------------------------------ | Input | Output | ------------------------------ | 0 | 1 | | 1 | 0 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/nand_gate.py
boolean_algebra/nand_gate.py
""" A NAND Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 1, and 1 (True) otherwise. It's similar to adding a NOT gate along with an AND gate. Following is the truth table of a NAND Gate: ------------------------------ | Input 1 | Input 2 | Output | ---------------...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/multiplexer.py
boolean_algebra/multiplexer.py
def mux(input0: int, input1: int, select: int) -> int: """ Implement a 2-to-1 Multiplexer. :param input0: The first input value (0 or 1). :param input1: The second input value (0 or 1). :param select: The select signal (0 or 1) to choose between input0 and input1. :return: The output based on t...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/boolean_algebra/nor_gate.py
boolean_algebra/nor_gate.py
""" A NOR Gate is a logic gate in boolean algebra which results in false(0) if any of the inputs is 1, and True(1) if all inputs are 0. Following is the truth table of a NOR Gate: Truth Table of NOR Gate: | Input 1 | Input 2 | Output | | 0 | 0 | 1 | | 0 | 1 | 0 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/docs/__init__.py
docs/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/docs/conf.py
docs/conf.py
from sphinx_pyproject import SphinxConfig project = SphinxConfig("../pyproject.toml", globalns=globals()).name
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/docs/source/__init__.py
docs/source/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/breadth_first_search_zero_one_shortest_path.py
graphs/breadth_first_search_zero_one_shortest_path.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/even_tree.py
graphs/even_tree.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/graph_list.py
graphs/graph_list.py
#!/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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/edmonds_karp_multiple_source_and_sink.py
graphs/edmonds_karp_multiple_source_and_sink.py
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 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/dinic.py
graphs/dinic.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/greedy_min_vertex_cover.py
graphs/greedy_min_vertex_cover.py
""" * 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/basic_graphs.py
graphs/basic_graphs.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/g_topological_sort.py
graphs/g_topological_sort.py
# 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 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/breadth_first_search_shortest_path.py
graphs/breadth_first_search_shortest_path.py
"""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": ["...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/connected_components.py
graphs/connected_components.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/gale_shapley_bigraph.py
graphs/gale_shapley_bigraph.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/depth_first_search_2.py
graphs/depth_first_search_2.py
#!/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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/greedy_best_first.py
graphs/greedy_best_first.py
""" 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,...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/minimum_path_sum.py
graphs/minimum_path_sum.py
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([ ....
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/bidirectional_search.py
graphs/bidirectional_search.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/deep_clone_graph.py
graphs/deep_clone_graph.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/bidirectional_breadth_first_search.py
graphs/bidirectional_breadth_first_search.py
""" 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,...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/dijkstra_binary_grid.py
graphs/dijkstra_binary_grid.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/frequent_pattern_graph_miner.py
graphs/frequent_pattern_graph_miner.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/check_cycle.py
graphs/check_cycle.py
""" 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 ""...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/tarjans_scc.py
graphs/tarjans_scc.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/prim.py
graphs/prim.py
"""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_): """ ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/multi_heuristic_astar.py
graphs/multi_heuristic_astar.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/articulation_points.py
graphs/articulation_points.py
# 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 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/breadth_first_search_shortest_path_2.py
graphs/breadth_first_search_shortest_path_2.py
"""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"], ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/markov_chain.py
graphs/markov_chain.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/lanczos_eigenvectors.py
graphs/lanczos_eigenvectors.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/ant_colony_optimization_algorithms.py
graphs/ant_colony_optimization_algorithms.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/bidirectional_a_star.py
graphs/bidirectional_a_star.py
""" 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], ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/kahns_algorithm_topo.py
graphs/kahns_algorithm_topo.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/matching_min_vertex_cover.py
graphs/matching_min_vertex_cover.py
""" * 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/dijkstra_2.py
graphs/dijkstra_2.py
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 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/scc_kosaraju.py
graphs/scc_kosaraju.py
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]: ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/page_rank.py
graphs/page_rank.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/graph_adjacency_matrix.py
graphs/graph_adjacency_matrix.py
#!/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. ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/minimum_spanning_tree_kruskal.py
graphs/minimum_spanning_tree_kruskal.py
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)] ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/kahns_algorithm_long.py
graphs/kahns_algorithm_long.py
# 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/minimum_spanning_tree_prims.py
graphs/minimum_spanning_tree_prims.py
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,...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/dijkstra_alternate.py
graphs/dijkstra_alternate.py
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 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/breadth_first_search_2.py
graphs/breadth_first_search_2.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/karger.py
graphs/karger.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/depth_first_search.py
graphs/depth_first_search.py
"""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 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/dijkstra_algorithm.py
graphs/dijkstra_algorithm.py
# 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 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/bellman_ford.py
graphs/bellman_ford.py
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 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/random_graph_generator.py
graphs/random_graph_generator.py
""" * 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/check_bipatrite.py
graphs/check_bipatrite.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/breadth_first_search.py
graphs/breadth_first_search.py
#!/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 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/minimum_spanning_tree_prims2.py
graphs/minimum_spanning_tree_prims2.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/__init__.py
graphs/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/eulerian_path_and_circuit_for_undirected_graph.py
graphs/eulerian_path_and_circuit_for_undirected_graph.py
# 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/dijkstra.py
graphs/dijkstra.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/boruvka.py
graphs/boruvka.py
"""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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/minimum_spanning_tree_kruskal2.py
graphs/minimum_spanning_tree_kruskal2.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/directed_and_undirected_weighted_graph.py
graphs/directed_and_undirected_weighted_graph.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/bi_directional_dijkstra.py
graphs/bi_directional_dijkstra.py
""" 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 ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/strongly_connected_components.py
graphs/strongly_connected_components.py
""" 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, ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/minimum_spanning_tree_boruvka.py
graphs/minimum_spanning_tree_boruvka.py
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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/graph_adjacency_list.py
graphs/graph_adjacency_list.py
#!/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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/graphs_floyd_warshall.py
graphs/graphs_floyd_warshall.py
# 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): ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/finding_bridges.py
graphs/finding_bridges.py
""" 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...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/a_star.py
graphs/a_star.py
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]]...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/tests/test_min_spanning_tree_prim.py
graphs/tests/test_min_spanning_tree_prim.py
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], ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/tests/__init__.py
graphs/tests/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphs/tests/test_min_spanning_tree_kruskal.py
graphs/tests/test_min_spanning_tree_kruskal.py
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], ...
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false