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
project_euler\problem_301\sol1.py
python
Python
""" Project Euler Problem 301: https://projecteuler.net/problem=301 Problem Statement: Nim is a game played with heaps of stones, where two players take it in turn to remove any number of stones from any heap until no stones remain. We'll consider the three-heap normal-play version of Nim, which works as follows: - A...
2,145
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
project_euler\problem_345\sol1.py
python
Python
""" Project Euler Problem 345: https://projecteuler.net/problem=345 Matrix Sum We define the Matrix Sum of a matrix as the maximum possible sum of matrix elements such that none of the selected elements share the same row or column. For example, the Matrix Sum of the matrix below equals 3315 ( = 863 + 383 + 343 + 95...
4,267
118
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
project_euler\problem_493\sol1.py
python
Python
""" Project Euler Problem 493: https://projecteuler.net/problem=493 70 coloured balls are placed in an urn, 10 for each of the seven rainbow colours. What is the expected number of distinct colours in 20 randomly picked balls? Give your answer with nine digits after the decimal point (a.bcdefghij). ----- This combin...
1,534
54
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
project_euler\problem_551\sol1.py
python
Python
""" Sum of digits sequence Problem 551 Let a(0), a(1),... be an integer sequence defined by: a(0) = 1 for n >= 1, a(n) is the sum of the digits of all preceding terms The sequence starts with 1, 1, 2, 4, 8, ... You are given a(10^6) = 31054319. Find a(10^15) """ ks = range(2, 20 + 1) base = [10**k for k i...
5,358
201
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
project_euler\problem_587\sol1.py
python
Python
""" Project Euler Problem 587: https://projecteuler.net/problem=587 A square is drawn around a circle as shown in the diagram below on the left. We shall call the blue shaded region the L-section. A line is drawn from the bottom left of the square to the top right as shown in the diagram on the right. We shall call th...
2,765
95
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
project_euler\problem_686\sol1.py
python
Python
""" Project Euler Problem 686: https://projecteuler.net/problem=686 2^7 = 128 is the first power of two whose leading digits are "12". The next power of two whose leading digits are "12" is 2^80. Define p(L,n) to be the nth-smallest value of j such that the base 10 representation of 2^j begins with the digits of L. ...
5,397
161
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
project_euler\problem_800\sol1.py
python
Python
""" Project Euler Problem 800: https://projecteuler.net/problem=800 An integer of the form p^q q^p with prime numbers p != q is called a hybrid-integer. For example, 800 = 2^5 5^2 is a hybrid-integer. We define C(n) to be the number of hybrid-integers less than or equal to n. You are given C(800) = 2 and C(800^800) =...
1,693
66
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
project_euler\README.md
readme
Markdown
# Project Euler Problems are taken from https://projecteuler.net/, the Project Euler. [Problems are licensed under CC BY-NC-SA 4.0](https://projecteuler.net/copyright). Project Euler is a series of challenging mathematical/computer programming problems that require more than just mathematical insights to solve. Proje...
5,512
119
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
quantum\q_fourier_transform.py
python
Python
""" Build the quantum fourier transform (qft) for a desire number of quantum bits using Qiskit framework. This experiment run in IBM Q simulator with 10000 shots. This circuit can be use as a building block to design the Shor's algorithm in quantum computing. As well as, quantum phase estimation among others. . Referen...
3,833
97
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
quantum\README.md
readme
Markdown
# Welcome to Quantum Algorithms Started at https://github.com/TheAlgorithms/Python/issues/1831 * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems * Google: https://research.google/teams/applied-science/quantum * IBM: https://qiskit.org and https://github.com/Qiskit * Rigetti: https://rigetti.com a...
1,156
24
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
README.md
readme
Markdown
<div align="center"> <!-- Title: --> <a href="https://github.com/TheAlgorithms/"> <img src="https://raw.githubusercontent.com/TheAlgorithms/website/1cd824df116b27029f17c2d1b42d81731f28a920/public/logo.svg" height="100"> </a> <h1><a href="https://github.com/TheAlgorithms/">The Algorithms</a> - Python</h1> <!-...
2,859
53
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scheduling\first_come_first_served.py
python
Python
# Implementation of First Come First Served scheduling algorithm # In this Algorithm we just care about the order that the processes arrived # without carring about their duration time # https://en.wikipedia.org/wiki/Scheduling_(computing)#First_come,_first_served from __future__ import annotations def calculate_wait...
3,879
109
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scheduling\highest_response_ratio_next.py
python
Python
""" Highest response ratio next (HRRN) scheduling is a non-preemptive discipline. It was developed as modification of shortest job next or shortest job first (SJN or SJF) to mitigate the problem of process starvation. https://en.wikipedia.org/wiki/Highest_response_ratio_next """ from statistics import mean import num...
4,107
120
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scheduling\job_sequence_with_deadline.py
python
Python
""" Given a list of tasks, each with a deadline and reward, calculate which tasks can be completed to yield the maximum reward. Each task takes one unit of time to complete, and we can only work on one task at a time. Once a task has passed its deadline, it can no longer be scheduled. Example : tasks_info = [(4, 20)...
1,958
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scheduling\job_sequencing_with_deadline.py
python
Python
def job_sequencing_with_deadlines(jobs: list) -> list: """ Function to find the maximum profit by doing jobs in a given time frame Args: jobs [list]: A list of tuples of (job_id, deadline, profit) Returns: max_profit [int]: Maximum profit that can be earned by doing jobs in a g...
1,464
48
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scheduling\multi_level_feedback_queue.py
python
Python
from collections import deque class Process: def __init__(self, process_name: str, arrival_time: int, burst_time: int) -> None: self.process_name = process_name # process name self.arrival_time = arrival_time # arrival time of the process # completion time of finished process or last int...
12,717
313
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scheduling\non_preemptive_shortest_job_first.py
python
Python
""" Non-preemptive Shortest Job First Shortest execution time process is chosen for the next execution. https://www.guru99.com/shortest-job-first-sjf-scheduling.html https://en.wikipedia.org/wiki/Shortest_job_next """ from __future__ import annotations from statistics import mean def calculate_waitingtime( arri...
3,604
111
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scheduling\round_robin.py
python
Python
""" Round Robin is a scheduling algorithm. In Round Robin each process is assigned a fixed time slot in a cyclic way. https://en.wikipedia.org/wiki/Round-robin_scheduling """ from __future__ import annotations from statistics import mean def calculate_waiting_times(burst_times: list[int]) -> list[int]: """ ...
2,270
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scheduling\shortest_job_first.py
python
Python
""" Shortest job remaining first Please note arrival time and burst Please use spaces to separate times entered. """ from __future__ import annotations import pandas as pd def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the wa...
4,873
154
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scripts\build_directory_md.py
python
Python
#!/usr/bin/env python3 import os from collections.abc import Iterator def good_file_paths(top_dir: str = ".") -> Iterator[str]: for dir_path, dir_names, filenames in os.walk(top_dir): dir_names[:] = [ d for d in dir_names if d != "scripts" and d[0] not in "._" and "ven...
1,834
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scripts\README.md
readme
Markdown
Dealing with the onslaught of Hacktoberfest * https://hacktoberfest.com Each year, October brings a swarm of new contributors participating in Hacktoberfest. This event has its pros and cons, but it presents a monumental workload for the few active maintainers of this repo. The maintainer workload is further impacte...
1,667
28
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scripts\validate_filenames.py
python
Python
#!/usr/bin/env python3 import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore[no-redef] filepaths = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" if upper_files := [file for file in filepaths i...
1,166
35
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
scripts\validate_solutions.py
python
Python
#!/usr/bin/env python3 # /// script # requires-python = ">=3.13" # dependencies = [ # "httpx", # "pytest", # ] # /// import hashlib import importlib.util import json import os import pathlib from types import ModuleType import httpx import pytest PROJECT_EULER_DIR_PATH = pathlib.Path.cwd().joinpath("project...
3,735
109
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\binary_search.py
python
Python
#!/usr/bin/env python3 """ Pure Python implementations of binary search algorithms For doctests run the following command: python3 -m doctest -v binary_search.py For manual testing run: python3 binary_search.py """ import bisect from itertools import pairwise def bisect_left( sorted_collection: list[int], ite...
15,024
435
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\binary_tree_traversal.py
python
Python
""" This is pure Python implementation of tree traversal algorithms """ from __future__ import annotations import queue class TreeNode: def __init__(self, data): self.data = data self.right = None self.left = None def build_tree() -> TreeNode: print("\n********Press N to stop enter...
9,333
306
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\double_linear_search.py
python
Python
from __future__ import annotations def double_linear_search(array: list[int], search_item: int) -> int: """ Iterate through the array from both sides to find the index of search_item. :param array: the array to be searched :param search_item: the item to be searched :return the index of search_it...
1,128
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\double_linear_search_recursion.py
python
Python
def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int: """ Iterate through the array to find the index of key using recursion. :param list_data: the list to be searched :param key: the key to be searched :param left: the index of first element :param right: the index of las...
946
36
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\exponential_search.py
python
Python
#!/usr/bin/env python3 """ Pure Python implementation of exponential search algorithm For more information, see the Wikipedia page: https://en.wikipedia.org/wiki/Exponential_search For doctests run the following command: python3 -m doctest -v exponential_search.py For manual testing run: python3 exponential_search....
3,808
114
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\fibonacci_search.py
python
Python
""" This is pure Python implementation of fibonacci search. Resources used: https://en.wikipedia.org/wiki/Fibonacci_search_technique For doctests run following command: python3 -m doctest -v fibonacci_search.py For manual testing run: python3 fibonacci_search.py """ from functools import lru_cache @lru_cache def ...
3,122
133
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\hill_climbing.py
python
Python
# https://en.wikipedia.org/wiki/Hill_climbing import math class SearchProblem: """ An interface to define search problems. The interface will be illustrated using the example of mathematical function. """ def __init__(self, x: int, y: int, step_size: int, function_to_optimize): """ ...
6,946
197
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\interpolation_search.py
python
Python
""" This is pure Python implementation of interpolation search algorithm """ def interpolation_search(sorted_collection: list[int], item: int) -> int | None: """ Searches for an item in a sorted collection by interpolation search algorithm. Args: sorted_collection: sorted list of integers ...
4,430
138
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\jump_search.py
python
Python
""" Pure Python implementation of the jump search algorithm. This algorithm iterates through a sorted collection with a step of n^(1/2), until the element compared is bigger than the one searched. It will then perform a linear search until it matches the wanted number. If not found, it returns -1. https://en.wikipedia...
1,875
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\linear_search.py
python
Python
""" This is a pure Python implementation of the linear search algorithm. For doctests run following command: python3 -m doctest -v linear_search.py For manual testing run: python3 linear_search.py """ def linear_search(sequence: list, target: int) -> int: """A pure Python implementation of a linear search algor...
2,471
78
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\median_of_medians.py
python
Python
""" A Python implementation of the Median of Medians algorithm to select pivots for quick_select, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted. Search in time complexity O(n) at any rank deterministically https://en.wikiped...
2,900
108
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\quick_select.py
python
Python
""" A Python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted https://en.wikipedia.org/wiki/Quickselect """ import random def _partition(data: list, pivot) -> tuple: """ ...
2,492
85
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\sentinel_linear_search.py
python
Python
""" This is pure Python implementation of sentinel linear search algorithm For doctests run following command: python -m doctest -v sentinel_linear_search.py or python3 -m doctest -v sentinel_linear_search.py For manual testing run: python sentinel_linear_search.py """ def sentinel_linear_search(sequence, target): ...
1,501
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\simple_binary_search.py
python
Python
""" Pure Python implementation of a binary search algorithm. For doctests run following command: python3 -m doctest -v simple_binary_search.py For manual testing run: python3 simple_binary_search.py """ from __future__ import annotations def binary_search(a_list: list[int], item: int) -> bool: """ >>> test...
1,737
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\simulated_annealing.py
python
Python
# https://en.wikipedia.org/wiki/Simulated_annealing import math import random from typing import Any from .hill_climbing import SearchProblem def simulated_annealing( search_prob, find_max: bool = True, max_x: float = math.inf, min_x: float = -math.inf, max_y: float = math.inf, min_y: float =...
5,392
138
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\tabu_search.py
python
Python
""" This is pure Python implementation of Tabu search algorithm for a Travelling Salesman Problem, that the distances between the cities are symmetric (the distance between city 'a' and city 'b' is the same between city 'b' and city 'a'). The TSP can be represented into a graph. The cities are represented by nodes and ...
11,112
293
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
searches\ternary_search.py
python
Python
""" This is a type of divide and conquer algorithm which divides the search space into 3 parts and finds the target value based on the property of the array or list (usually monotonic property). Time Complexity : O(log3 N) Space Complexity : O(1) """ from __future__ import annotations # This is the precision for th...
5,154
174
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\bead_sort.py
python
Python
""" Bead sort only works for sequences of non-negative integers. https://en.wikipedia.org/wiki/Bead_sort """ def bead_sort(sequence: list) -> list: """ >>> bead_sort([6, 11, 12, 4, 1, 5]) [1, 4, 5, 6, 11, 12] >>> bead_sort([9, 8, 7, 6, 5, 4 ,3, 2, 1]) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> bead_sor...
1,333
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\binary_insertion_sort.py
python
Python
""" This is a pure Python implementation of the binary insertion sort algorithm For doctests run following command: python -m doctest -v binary_insertion_sort.py or python3 -m doctest -v binary_insertion_sort.py For manual testing run: python binary_insertion_sort.py """ def binary_insertion_sort(collection: list) ...
2,067
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\bitonic_sort.py
python
Python
""" Python program for Bitonic Sort. Note that this program works only when size of input is a power of 2. """ from __future__ import annotations def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None: """Compare the value at given index1 and index2 of the array and swap them as p...
3,102
98
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\bogo_sort.py
python
Python
""" This is a pure Python implementation of the bogosort algorithm, also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort. Bogosort generates random permutations until it guesses the correct one. More info on: https://en.wikipedia.org/wiki/Bogosort For doctests run following command: pyt...
1,396
48
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\bubble_sort.py
python
Python
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 in ascending order Ex...
5,184
139
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\bucket_sort.py
python
Python
#!/usr/bin/env python3 """ Illustrate how to implement bucket sort algorithm. Author: OMKAR PATHAK This program will illustrate how to implement bucket sort algorithm Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each buc...
3,419
102
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\circle_sort.py
python
Python
""" This is a Python implementation of the circle sort algorithm For doctests run following command: python3 -m doctest -v circle_sort.py For manual testing run: python3 circle_sort.py """ def circle_sort(collection: list) -> list: """A pure Python implementation of circle sort algorithm :param collection:...
2,360
87
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\cocktail_shaker_sort.py
python
Python
""" 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...
2,035
69
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\comb_sort.py
python
Python
""" This is pure Python implementation of comb sort algorithm. Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort algorithm. In bubble sort, distance (or gap) between ...
1,912
63
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\counting_sort.py
python
Python
""" This is pure Python implementation of counting sort algorithm For doctests run following command: python -m doctest -v counting_sort.py or python3 -m doctest -v counting_sort.py For manual testing run: python counting_sort.py """ def counting_sort(collection): """Pure implementation of counting sort algorithm...
2,338
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\cycle_sort.py
python
Python
""" Code contributed by Honey Sharma Source: https://en.wikipedia.org/wiki/Cycle_sort """ def cycle_sort(array: list) -> list: """ >>> cycle_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> cycle_sort([-4, 20, 0, -50, 100, -1]) [-50, -4, -1, 0, 20, 100] >>> cycle_sort([-.1, -.2, 1.3, -.8]) [-0.8, -0....
1,297
54
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\cyclic_sort.py
python
Python
""" This is a pure Python implementation of the Cyclic Sort algorithm. For doctests run following command: python -m doctest -v cyclic_sort.py or python3 -m doctest -v cyclic_sort.py For manual testing run: python cyclic_sort.py or python3 cyclic_sort.py """ def cyclic_sort(nums: list[int]) -> list[int]: """ ...
1,593
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\double_sort.py
python
Python
from typing import Any def double_sort(collection: list[Any]) -> list[Any]: """This sorting algorithm sorts an array using the principle of bubble sort, but does it both from left to right and right to left. Hence, it's called "Double sort" :param collection: mutable ordered sequence of elements :...
1,845
45
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\dutch_national_flag_sort.py
python
Python
""" A pure implementation of Dutch national flag (DNF) sort algorithm in Python. Dutch National Flag algorithm is an algorithm originally designed by Edsger Dijkstra. It is the most optimal sort for 3 unique values (eg. 0, 1, 2) in a sequence. DNF can sort a sequence of n size with [0 <= a[i] <= 2] at guaranteed O(n) ...
3,761
99
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\exchange_sort.py
python
Python
def exchange_sort(numbers: list[int]) -> list[int]: """ Uses exchange sort to sort a list of numbers. Source: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort >>> exchange_sort([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> exchange_sort([-1, -2, -3]) [-3, -2, -1] >>> exchange_sort([1...
923
28
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\external_sort.py
python
Python
#!/usr/bin/env python # # Sort large text files in a minimum amount of memory # import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number...
4,392
155
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\gnome_sort.py
python
Python
""" 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...
1,444
57
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\heap_sort.py
python
Python
""" A pure Python implementation of the heap sort algorithm. """ def heapify(unsorted: list[int], index: int, heap_size: int) -> None: """ :param unsorted: unsorted list containing integers numbers :param index: index :param heap_size: size of the heap :return: None >>> unsorted = [1, 4, 3, 5,...
2,049
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\insertion_sort.py
python
Python
""" A pure Python implementation of the insertion sort algorithm This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward...
2,269
70
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\intro_sort.py
python
Python
""" Introspective Sort is a hybrid sort (Quick Sort + Heap Sort + Insertion Sort) if the size of the list is under 16, use insertion sort https://en.wikipedia.org/wiki/Introsort """ import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: """ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14...
6,634
193
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\iterative_merge_sort.py
python
Python
""" Implementation of iterative merge sort in Python Author: Aman Gupta For doctests run following command: python3 -m doctest -v iterative_merge_sort.py For manual testing run: python3 iterative_merge_sort.py """ from __future__ import annotations def merge(input_list: list, low: int, mid: int, high: int) -> list...
2,687
94
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\merge_insertion_sort.py
python
Python
""" 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...
5,882
201
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\merge_sort.py
python
Python
""" This is a pure Python implementation of the merge sort algorithm. For doctests run following command: python -m doctest -v merge_sort.py or python3 -m doctest -v merge_sort.py For manual testing run: python merge_sort.py """ def merge_sort(collection: list) -> list: """ Sorts a list using the merge sort ...
1,789
65
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\msd_radix_sort.py
python
Python
""" 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...
4,841
162
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\natural_sort.py
python
Python
from __future__ import annotations import re def natural_sort(input_list: list[str]) -> list[str]: """ Sort the given list of strings in the way that humans expect. The normal Python sort algorithm sorts lexicographically, so you might not get the results that you expect... >>> example1 = ['2 f...
1,243
37
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\odd_even_sort.py
python
Python
""" Odd even sort implementation. https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort """ def odd_even_sort(input_list: list) -> list: """ Sort input with odd even sort. This algorithm uses the same idea of bubblesort, but by first dividing in two phase (odd and even). Originally developed for u...
1,794
52
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\odd_even_transposition_parallel.py
python
Python
""" This is an implementation of odd-even transposition sort. It works by performing a series of parallel swaps between odd and even pairs of variables in the list. This implementation represents each variable in the list with a process and each process communicates with its neighboring processes in the list to perfo...
6,074
193
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\odd_even_transposition_single_threaded.py
python
Python
""" Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort This is a non-parallelized implementation of odd-even transposition sort. Normally the swaps in each set happen simultaneously, without that the algorithm is no better than bubble sort. """ def odd_even_transposition(arr: list) -> list: """ >>>...
921
34
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\pancake_sort.py
python
Python
""" This is a pure Python implementation of the pancake sort algorithm For doctests run following command: python3 -m doctest -v pancake_sort.py or python -m doctest -v pancake_sort.py For manual testing run: python pancake_sort.py """ def pancake_sort(arr): """Sort Array with Pancake Sort. :param arr: Collec...
1,131
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\patience_sort.py
python
Python
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge """ A pure Python implementation of the patience sort algorithm For more information: https://en.wikipedia.org/wiki/Patience_sorting This algorithm is based on the card game patience For d...
1,759
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\pigeon_sort.py
python
Python
""" This is an implementation of Pigeon Hole Sort. For doctests run following command: python3 -m doctest -v pigeon_sort.py or python -m doctest -v pigeon_sort.py For manual testing run: python pigeon_sort.py """ from __future__ import annotations def pigeon_sort(array: list[int]) -> list[int]: """ Impleme...
1,506
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\pigeonhole_sort.py
python
Python
# Python program to implement Pigeonhole Sorting in python # Algorithm for the pigeonhole sorting def pigeonhole_sort(a): """ >>> a = [8, 3, 2, 7, 4, 6, 8] >>> b = sorted(a) # a nondestructive sort >>> pigeonhole_sort(a) # a destructive sort >>> a == b True >>> pigeonhole_sort([]) ...
1,258
50
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\quick_sort.py
python
Python
""" A pure Python implementation of the quick sort algorithm For doctests run following command: python3 -m doctest -v quick_sort.py For manual testing run: python3 quick_sort.py """ from __future__ import annotations from random import randrange def quick_sort(collection: list) -> list: """A pure Python impl...
1,661
53
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\quick_sort_3_partition.py
python
Python
def quick_sort_3partition(sorting: list, left: int, right: int) -> None: """ " Python implementation of quick sort algorithm with 3-way partition. The idea of 3-way quick sort is based on "Dutch National Flag algorithm". :param sorting: sort list :param left: left endpoint of sorting :param rig...
3,876
125
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\radix_sort.py
python
Python
""" This is a pure Python implementation of the radix sort algorithm Source: https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations RADIX = 10 def radix_sort(list_of_ints: list[int]) -> list[int]: """ Examples: >>> radix_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> radix_...
1,261
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\README.md
readme
Markdown
# Sorting Algorithms Sorting is the process of putting data in a specific order. The way to arrange data in a specific order is specified by the sorting algorithm. The most typical orders are lexical or numerical. The significance of sorting lies in the fact that, if data is stored in a sorted manner, data searching ca...
757
12
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\recursive_insertion_sort.py
python
Python
""" A recursive implementation of the insertion sort algorithm """ from __future__ import annotations def rec_insertion_sort(collection: list, n: int): """ Given a collection of numbers and its length, sorts the collections in ascending order :param collection: A mutable collection of comparable ele...
1,855
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\recursive_mergesort_array.py
python
Python
"""A merge sort which accepts an array as input and recursively splits an array in half and sorts and combines them. """ """https://en.wikipedia.org/wiki/Merge_sort """ def merge(arr: list[int]) -> list[int]: """Return a sorted array. >>> merge([10,9,8,7,6,5,4,3,2,1]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ...
2,188
65
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\recursive_quick_sort.py
python
Python
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]]), ...
507
23
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\selection_sort.py
python
Python
def selection_sort(collection: list[int]) -> list[int]: """ Sorts a list in ascending order using the selection sort algorithm. :param collection: A list of integers to be sorted. :return: The sorted list. Examples: >>> selection_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> selection_sor...
1,020
35
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\shell_sort.py
python
Python
""" https://en.wikipedia.org/wiki/Shellsort#Pseudocode """ def shell_sort(collection: list[int]) -> list[int]: """Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered b...
1,200
41
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\shrink_shell_sort.py
python
Python
""" 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...
1,950
66
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\slowsort.py
python
Python
""" Slowsort is a sorting algorithm. It is of humorous nature and not useful. It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis (a parody of optimal al...
1,867
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\stalin_sort.py
python
Python
""" Stalin Sort algorithm: Removes elements that are out of order. Elements that are not greater than or equal to the previous element are discarded. Reference: https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420 """ def stalin_sort(sequence: list[int]) -> list[int]: """ Sorts a list usi...
1,041
48
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\stooge_sort.py
python
Python
def stooge_sort(arr: list[int]) -> list[int]: """ Examples: >>> stooge_sort([18.1, 0, -7.1, -1, 2, 2]) [-7.1, -1, 0, 2, 2, 18.1] >>> stooge_sort([]) [] """ stooge(arr, 0, len(arr) - 1) return arr def stooge(arr: list[int], i: int, h: int) -> None: if i >= h: return ...
1,026
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\strand_sort.py
python
Python
import operator def strand_sort(arr: list, reverse: bool = False, solution: list | None = None) -> list: """ Strand sort implementation source: https://en.wikipedia.org/wiki/Strand_sort :param arr: Unordered input list :param reverse: Descent ordering flag :param solution: Ordered items conta...
1,430
52
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\tim_sort.py
python
Python
def binary_search(lst, item, start, end): if start == end: return start if lst[start] > item else start + 1 if start > end: return start mid = (start + end) // 2 if lst[mid] < item: return binary_search(lst, item, mid + 1, end) elif lst[mid] > item: return binary_sea...
1,955
83
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\topological_sort.py
python
Python
"""Topological Sort.""" # a # / \ # b c # / \ # d e edges: dict[str, list[str]] = { "a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": [], } vertices: list[str] = ["a", "b", "c", "d", "e"] def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]: ""...
1,138
42
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\tree_sort.py
python
Python
""" Tree_sort algorithm. Build a Binary Search Tree and then iterate thru it to get a sorted list. """ from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: val: int left: Node | None = None right: Node | None = None def __...
1,689
73
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\unknown_sort.py
python
Python
""" Python implementation of a sort algorithm. Best Case Scenario : O(n) Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are already O(n) """ def merge_sort(collection: list) -> list: """Pure implementation of the fastest merge sort algorithm in Python :param collection: some...
1,146
41
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
sorts\wiggle_sort.py
python
Python
""" Wiggle Sort. Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... For example: if input numbers = [3, 5, 2, 1, 6, 4] one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4]. """ def wiggle_sort(nums: list) -> list: """ Python implementation of wiggle. Example: ...
967
39
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
strings\aho_corasick.py
python
Python
from __future__ import annotations from collections import deque class Automaton: def __init__(self, keywords: list[str]): self.adlist: list[dict] = [] self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []} ) for keyword in keywords: ...
3,675
97
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
strings\alternative_string_arrange.py
python
Python
def alternative_string_arrange(first_str: str, second_str: str) -> str: """ Return the alternative arrangements of the two strings. :param first_str: :param second_str: :return: String >>> alternative_string_arrange("ABCD", "XY") 'AXBYCD' >>> alternative_string_arrange("XY", "ABCD") ...
1,073
32
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
strings\anagrams.py
python
Python
from __future__ import annotations import collections import pprint from pathlib import Path def signature(word: str) -> str: """ Return a word's frequency-based signature. >>> signature("test") 'e1s1t2' >>> signature("this is a test") ' 3a1e1h1i2s3t3' >>> signature("finaltest") 'a1e...
1,385
52
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
strings\autocomplete_using_trie.py
python
Python
from __future__ import annotations END = "#" class Trie: def __init__(self) -> None: self._trie: dict = {} def insert_word(self, text: str) -> None: trie = self._trie for char in text: if char not in trie: trie[char] = {} trie = trie[char] ...
1,554
66
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
strings\barcode_validator.py
python
Python
""" https://en.wikipedia.org/wiki/Check_digit#Algorithms """ def get_check_digit(barcode: int) -> int: """ Returns the last digit of barcode by excluding the last digit first and then computing to reach the actual last digit from the remaining 12 digits. >>> get_check_digit(8718452538119) 9 ...
2,269
90
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
strings\bitap_string_match.py
python
Python
""" Bitap exact string matching https://en.wikipedia.org/wiki/Bitap_algorithm Searches for a pattern inside text, and returns the index of the first occurrence of the pattern. Both text and pattern consist of lowercase alphabetical characters only. Complexity: O(m*n) n = length of text m = length of pattern ...
2,449
80
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
strings\boyer_moore_search.py
python
Python
""" The algorithm finds the pattern in given text using following rule. The bad-character rule considers the mismatched character in Text. The next occurrence of that character to the left in Pattern is found, If the mismatched character occurs to the left in Pattern, a shift is proposed that aligns text block and pa...
3,235
105
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
strings\camel_case_to_snake_case.py
python
Python
def camel_to_snake_case(input_str: str) -> str: """ Transforms a camelCase (or PascalCase) string to snake_case >>> camel_to_snake_case("someRandomString") 'some_random_string' >>> camel_to_snake_case("SomeRandomStr#ng") 'some_random_str_ng' >>> camel_to_snake_case("123someRandom123String...
1,644
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
strings\can_string_be_rearranged_as_palindrome.py
python
Python
# Created by susmith98 from collections import Counter from timeit import timeit # Problem Description: # Check if characters of the given string can be rearranged to form a palindrome. # Counter is faster for long strings and non-Counter is faster for short strings. def can_string_be_rearranged_as_palindrome_count...
4,071
114