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
maths\special_numbers\carmichael_number.py
python
Python
""" == Carmichael Numbers == A number n is said to be a Carmichael number if it satisfies the following modular arithmetic condition: power(b, n-1) MOD n = 1, for all b ranging from 1 to n such that b and n are relatively prime, i.e, gcd(b, n) = 1 Examples of Carmichael Numbers: 561, 1105, ... https://en....
2,135
87
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\catalan_number.py
python
Python
""" Calculate the nth Catalan number Source: https://en.wikipedia.org/wiki/Catalan_number """ def catalan(number: int) -> int: """ :param number: nth catalan number to calculate :return: the nth catalan number Note: A catalan number is only defined for positive integers >>> catalan(5) ...
1,238
54
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\hamming_numbers.py
python
Python
""" A Hamming number is a positive integer of the form 2^i*3^j*5^k, for some non-negative integers i, j, and k. They are often referred to as regular numbers. More info at: https://en.wikipedia.org/wiki/Regular_number. """ def hamming(n_element: int) -> list: """ This function creates an ordered list of n len...
1,921
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\happy_number.py
python
Python
def is_happy_number(number: int) -> bool: """ A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. :param number: The number to check for happiness. :return: True if the number is a happy number, False otherwise. >>> is_happy_number(19) ...
1,416
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\harshad_numbers.py
python
Python
""" A harshad number (or more specifically an n-harshad number) is a number that's divisible by the sum of its digits in some given base n. Reference: https://en.wikipedia.org/wiki/Harshad_number """ def int_to_base(number: int, base: int) -> str: """ Convert a given positive decimal integer to base 'base'. ...
4,668
167
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\hexagonal_number.py
python
Python
""" == Hexagonal Number == The nth hexagonal number hn is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. https://en.wikipedia.org/wiki/Hexagonal_number """ # Author : Akshay Dubey (h...
1,405
50
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\krishnamurthy_number.py
python
Python
""" == Krishnamurthy Number == It is also known as Peterson Number A Krishnamurthy Number is a number whose sum of the factorial of the digits equals to the original number itself. For example: 145 = 1! + 4! + 5! So, 145 is a Krishnamurthy Number """ def factorial(digit: int) -> int: """ >>> factorial(3...
1,121
50
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\perfect_number.py
python
Python
""" == Perfect Number == In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 ==> divisors[1, 2, 3, 6] Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: ...
2,184
80
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\polygonal_numbers.py
python
Python
def polygonal_num(num: int, sides: int) -> int: """ Returns the `num`th `sides`-gonal number. It is assumed that `num` >= 0 and `sides` >= 3 (see for reference https://en.wikipedia.org/wiki/Polygonal_number). >>> polygonal_num(0, 3) 0 >>> polygonal_num(3, 3) 6 >>> polygonal_num(5, 4) ...
946
33
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\pronic_number.py
python
Python
""" == Pronic Number == A number n is said to be a Proic number if there exists an integer m such that n = m * (m + 1) Examples of Proic Numbers: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110 ... https://en.wikipedia.org/wiki/Pronic_number """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) def is_pronic(num...
1,364
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\proth_number.py
python
Python
""" Calculate the nth Proth number Source: https://handwiki.org/wiki/Proth_number """ import math def proth(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Proth number Note: indexing starts at 1 i.e. proth(1) gives the first Proth number...
3,409
126
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\triangular_numbers.py
python
Python
""" A triangular number or triangle number counts objects arranged in an equilateral triangle. This module provides a function to generate n'th triangular number. For more information about triangular numbers, refer to: https://en.wikipedia.org/wiki/Triangular_number """ def triangular_number(position: int) -> int: ...
1,084
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\ugly_numbers.py
python
Python
""" Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, 1 is included. Given an integer n, we have to find the nth ugly number. For more details, refer this article https://www.geeksforgeeks.org/ugly-numbers...
1,406
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\special_numbers\weird_number.py
python
Python
""" https://en.wikipedia.org/wiki/Weird_number Fun fact: The set of weird numbers has positive asymptotic density. """ from math import sqrt def factors(number: int) -> list[int]: """ >>> factors(12) [1, 2, 3, 4, 6] >>> factors(1) [1] >>> factors(100) [1, 2, 4, 5, 10, 20, 25, 50] # ...
2,101
102
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\sum_of_arithmetic_series.py
python
Python
# DarkCoder def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float: """ Find the sum of n terms in an arithmetic progression. >>> sum_of_series(1, 1, 10) 55.0 >>> sum_of_series(1, 10, 100) 49600.0 """ total = (num_of_terms / 2) * (2 * first_term + (num_of_terms...
533
24
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\sum_of_digits.py
python
Python
def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = abs(n) res = 0 while n > 0: res += n % 10 n //= 10 return re...
1,819
75
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\sum_of_geometric_progression.py
python
Python
def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: """ " Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 >>> sum_of_geometric_progression(1, 10, 5) 11111.0 >>> sum_of_geometric_progre...
937
29
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\sum_of_harmonic_series.py
python
Python
def sum_of_harmonic_progression( first_term: float, common_difference: float, number_of_terms: int ) -> float: """ https://en.wikipedia.org/wiki/Harmonic_progression_(mathematics) Find the sum of n terms in an harmonic progression. The calculation starts with the first_term and loops adding the co...
1,018
30
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\sumset.py
python
Python
""" Calculates the SumSet of two sets of numbers (A and B) Source: https://en.wikipedia.org/wiki/Sumset """ def sumset(set_a: set, set_b: set) -> set: """ :param first set: a set of numbers :param second set: a set of numbers :return: the nth number in Sylvester's sequence >>> sumset({1, 2...
907
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\sylvester_sequence.py
python
Python
""" Calculates the nth number in Sylvester's sequence Source: https://en.wikipedia.org/wiki/Sylvester%27s_sequence """ def sylvester(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Sylvester's sequence >>> sylvester(8) 113423713055...
1,120
45
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\tanh.py
python
Python
""" This script demonstrates the implementation of the tangent hyperbolic or tanh function. The function takes a vector of K real numbers as input and then (e^x - e^(-x))/(e^x + e^(-x)). After through tanh, the element of the vector mostly -1 between 1. Script inspired from its corresponding Wikipedia article https:/...
1,175
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\test_factorial.py
test
Python
# /// script # requires-python = ">=3.13" # dependencies = [ # "pytest", # ] # /// import pytest from maths.factorial import factorial, factorial_recursive @pytest.mark.parametrize("function", [factorial, factorial_recursive]) def test_zero(function): assert function(0) == 1 @pytest.mark.parametrize("func...
1,065
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\test_prime_check.py
test
Python
""" Minimalist file that allows pytest to find and run the Test unittest. For details, see: https://doc.pytest.org/en/latest/goodpractices.html#conventions-for-python-test-discovery """ from .prime_check import Test Test()
234
9
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\three_sum.py
python
Python
""" https://en.wikipedia.org/wiki/3SUM """ def three_sum(nums: list[int]) -> list[list[int]]: """ Find all unique triplets in a sorted array of integers that sum up to zero. Args: nums: A sorted list of integers. Returns: A list of lists containing unique triplets that sum up to zero...
1,287
48
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\trapezoidal_rule.py
python
Python
""" Numerical integration or quadrature for a smooth function f with known values at x_i """ def trapezoidal_rule(boundary, steps): """ Implements the extended trapezoidal rule for numerical integration. The function f(x) is provided below. :param boundary: List containing the lower and upper bounds ...
2,613
106
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\triplet_sum.py
python
Python
""" Given an array of integers and another integer target, we are required to find a triplet from the array such that it's sum is equal to the target. """ from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def make_dataset() -> tuple[list[int],...
2,548
91
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\twin_prime.py
python
Python
""" == Twin Prime == A number n+2 is said to be a Twin prime of number n if both n and n+2 are prime. Examples of Twin pairs: (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), ... https://en.wikipedia.org/wiki/Twin_prime """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_check impo...
1,177
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\two_pointer.py
python
Python
""" Given a sorted array of integers, return indices of the two numbers such that they add up to a specific target using the two pointers technique. You may assume that each input would have exactly one solution, and you may not use the same element twice. This is an alternative solution of the two-sum problem, which...
1,548
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\two_sum.py
python
Python
""" Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0,...
1,151
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\volume.py
python
Python
""" Find the volume of various shapes. * https://en.wikipedia.org/wiki/Volume * https://en.wikipedia.org/wiki/Spherical_cap """ from __future__ import annotations from math import pi, pow # noqa: A004 def vol_cube(side_length: float) -> float: """ Calculate the Volume of a Cube. >>> vol_cube(1) 1...
19,014
568
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
maths\zellers_congruence.py
python
Python
import argparse import datetime def zeller(date_input: str) -> str: """ | Zellers Congruence Algorithm | Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month: >>> zeller('13-31...
4,458
165
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\binary_search_matrix.py
python
Python
def binary_search(array: list, lower_bound: int, upper_bound: int, value: int) -> int: """ This function carries out Binary search on a 1d array and return -1 if it do not exist array: A 1d sorted array value : the value meant to be searched >>> matrix = [1, 4, 7, 11, 15] >>> binary_search(m...
1,763
58
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\count_islands_in_matrix.py
python
Python
# An island in matrix is a group of linked areas, all having the same value. # This code counts number of islands in a given matrix, with including diagonal # connections. class Matrix: # Public class to implement a graph def __init__(self, row: int, col: int, graph: list[list[bool]]) -> None: self.ROW =...
1,517
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\count_negative_numbers_in_sorted_matrix.py
python
Python
""" Given an matrix of numbers in which all rows and all columns are sorted in decreasing order, return the number of negative numbers in grid. Reference: https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix """ def generate_large_matrix() -> list[list[int]]: """ >>> generate_large_matrix(...
4,398
152
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\count_paths.py
python
Python
""" Given a grid, where you start from the top left position [0, 0], you want to find how many paths you can take to get to the bottom right position. start here -> 0 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 <- finish here how many 'distinct' paths can you take t...
2,221
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\cramers_rule_2x2.py
python
Python
# https://www.chilimath.com/lessons/advanced-algebra/cramers-rule-with-two-variables # https://en.wikipedia.org/wiki/Cramer%27s_rule def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> tuple[float, float]: """ Solves the system of linear equation in 2 variables. :param: equation1: list of ...
3,106
84
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\inverse_of_matrix.py
python
Python
from __future__ import annotations from decimal import Decimal from numpy import array def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]: """ A matrix multiplied with its inverse gives the identity matrix. This function finds the inverse of a 2x2 and 3x3 matrix. If the determinan...
6,082
156
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\largest_square_area_in_matrix.py
python
Python
""" Question: Given a binary matrix mat of size n * m, find out the maximum size square sub-matrix with all 1s. --- Example 1: Input: n = 2, m = 2 mat = [[1, 1], [1, 1]] Output: 2 Explanation: The maximum size of the square sub-matrix is 2. The matrix itself is the maximum sized sub-matrix in this case. --- ...
5,789
189
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\matrix_based_game.py
python
Python
""" Matrix-Based Game Script ========================= This script implements a matrix-based game where players interact with a grid of elements. The primary goals are to: - Identify connected elements of the same type from a selected position. - Remove those elements, adjust the matrix by simulating gravity, and reorg...
8,856
285
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\matrix_class.py
python
Python
# An OOP approach to representing and manipulating matrices from __future__ import annotations class Matrix: """ Matrix object generated from a 2D array where each element is an array representing a row. Rows can contain type int or float. Common operations and information available. >>> rows...
11,625
367
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\matrix_equalization.py
python
Python
from sys import maxsize def array_equalization(vector: list[int], step_size: int) -> int: """ This algorithm equalizes all elements of the input vector to a common value, by making the minimal number of "updates" under the constraint of a step size (step_size). >>> array_equalization([1, 1, 6, 2,...
1,785
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\matrix_multiplication_recursion.py
python
Python
# @Author : ojas-wani # @File : matrix_multiplication_recursion.py # @Date : 10/06/2023 """ Perform matrix multiplication using a recursive algorithm. https://en.wikipedia.org/wiki/Matrix_multiplication """ # type Matrix = list[list[int]] # psf/black currenttly fails on this line Matrix = list[list[int]] ma...
5,329
182
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\matrix_operation.py
python
Python
""" Functions for 2D matrix operations """ from __future__ import annotations from typing import Any def add(*matrix_s: list[list[int]]) -> list[list[int]]: """ >>> add([[1,2],[3,4]],[[2,3],[4,5]]) [[3, 5], [7, 9]] >>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]]) [[3.2, 5.4], [7, 9]] >>> add([[1, 2]...
6,310
204
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\max_area_of_island.py
python
Python
""" Given an two dimensional binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the island. Return the maximum area of a...
3,533
113
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\median_matrix.py
python
Python
""" https://en.wikipedia.org/wiki/Median """ def median(matrix: list[list[int]]) -> int: """ Calculate the median of a sorted matrix. Args: matrix: A 2D matrix of integers. Returns: The median value of the matrix. Examples: >>> matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]] ...
776
39
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\nth_fibonacci_using_matrix_exponentiation.py
python
Python
""" Implementation of finding nth fibonacci number using matrix exponentiation. Time Complexity is about O(log(n)*8), where 8 is the complexity of matrix multiplication of size 2 by 2. And on the other hand complexity of bruteforce solution is O(n). As we know f[n] = f[n-1] + f[n-1] Converting to matrix, [f(n),...
2,881
95
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\pascal_triangle.py
python
Python
""" This implementation demonstrates how to generate the elements of a Pascal's triangle. The element havingva row index of r and column index of c can be derivedvas follows: triangle[r][c] = triangle[r-1][c-1]+triangle[r-1][c] A Pascal's triangle is a triangular array containing binomial coefficients. https://en.wiki...
6,372
190
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\rotate_matrix.py
python
Python
""" In this problem, we want to rotate the matrix elements by 90, 180, 270 (counterclockwise) Discussion in stackoverflow: https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array """ from __future__ import annotations def make_matrix(row_size: int = 4) -> list[list[int]]: """ >>> ...
2,834
102
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\searching_in_sorted_matrix.py
python
Python
from __future__ import annotations def search_in_a_sorted_matrix(mat: list[list[int]], m: int, n: int, key: float) -> None: """ >>> search_in_a_sorted_matrix( ... [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 5) Key 5 found at row- 1 column- 2 >>> search_in_a_sorted_matrix( ......
1,319
43
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\sherman_morrison.py
python
Python
from __future__ import annotations from typing import Any class Matrix: """ <class Matrix> Matrix structure. """ def __init__(self, row: int, column: int, default_value: float = 0) -> None: """ <method Matrix.__init__> Initialize matrix with given size and default value. ...
8,487
268
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\spiral_print.py
python
Python
""" This program print the matrix in spiral form. This problem has been solved through recursive way. Matrix must satisfy below conditions i) matrix should be only one or two dimensional ii) number of column of all rows should be equal """ def check_matrix(matrix: list[list[int]]) -> bool: #...
3,704
134
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\tests\test_matrix_operation.py
test
Python
""" Testing here assumes that numpy and linalg is ALWAYS correct!!!! If running from PyCharm you can place the following line in "Additional Arguments" for the pytest run configuration -vv -m mat_ops -p no:cacheprovider """ import logging # standard libraries import sys import numpy as np import pytest # Custom/lo...
4,105
121
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
matrix\validate_sudoku_board.py
python
Python
""" LeetCode 36. Valid Sudoku https://leetcode.com/problems/valid-sudoku/ https://en.wikipedia.org/wiki/Sudoku Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: - Each row must contain the digits 1-9 without repetition. - Each column must contain ...
6,028
168
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
networking_flow\ford_fulkerson.py
python
Python
""" 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], ...
3,103
114
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
networking_flow\minimum_cut.py
python
Python
# 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...
1,719
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\binary_step.py
python
Python
""" This script demonstrates the implementation of the Binary Step function. It's an activation function in which the neuron is activated if the input is positive or 0, else it is deactivated It's a simple activation function which is mentioned in this wikipedia article: https://en.wikipedia.org/wiki/Activation_funct...
892
36
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\exponential_linear_unit.py
python
Python
""" Implements the Exponential Linear Unit or ELU function. The function takes a vector of K real numbers and a real number alpha as input and then applies the ELU function to each element of the vector. Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Rectifier_(neural_networks)...
1,271
41
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\gaussian_error_linear_unit.py
python
Python
""" This script demonstrates an implementation of the Gaussian Error Linear Unit function. * https://en.wikipedia.org/wiki/Activation_function#Comparison_of_activation_functions The function takes a vector of K real numbers as input and returns x * sigmoid(1.702*x). Gaussian Error Linear Unit (GELU) is a high-performi...
1,542
52
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\leaky_rectified_linear_unit.py
python
Python
""" Leaky Rectified Linear Unit (Leaky ReLU) Use Case: Leaky ReLU addresses the problem of the vanishing gradient. For more detailed information, you can refer to the following link: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Leaky_ReLU """ import numpy as np def leaky_rectified_linear_unit(vector: n...
1,185
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\mish.py
python
Python
""" Mish Activation Function Use Case: Improved version of the ReLU activation function used in Computer Vision. For more detailed information, you can refer to the following link: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Mish """ import numpy as np from .softplus import softplus def mish(vector: ...
1,082
42
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\rectified_linear_unit.py
python
Python
""" This script demonstrates the implementation of the ReLU function. It's a kind of activation function defined as the positive part of its argument in the context of neural network. The function takes a vector of K real numbers as input and then argmax(x, 0). After through ReLU, the element of the vector always 0 or...
1,127
42
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\scaled_exponential_linear_unit.py
python
Python
""" Implements the Scaled Exponential Linear Unit or SELU function. The function takes a vector of K real numbers and two real numbers alpha(default = 1.6732) & lambda (default = 1.0507) as input and then applies the SELU function to each element of the vector. SELU is a self-normalizing activation function. It is a va...
1,552
45
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\soboleva_modified_hyperbolic_tangent.py
python
Python
""" This script implements the Soboleva Modified Hyperbolic Tangent function. The function applies the Soboleva Modified Hyperbolic Tangent function to each element of the vector. More details about the activation function can be found on: https://en.wikipedia.org/wiki/Soboleva_modified_hyperbolic_tangent """ import...
1,649
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\softplus.py
python
Python
""" Softplus Activation Function Use Case: The Softplus function is a smooth approximation of the ReLU function. For more detailed information, you can refer to the following link: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Softplus """ import numpy as np def softplus(vector: np.ndarray) -> np.ndarra...
1,003
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\squareplus.py
python
Python
""" Squareplus Activation Function Use Case: Squareplus designed to enhance positive values and suppress negative values. For more detailed information, you can refer to the following link: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Squareplus """ import numpy as np def squareplus(vector: np.ndarray,...
1,116
39
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\activation_functions\swish.py
python
Python
""" This script demonstrates the implementation of the Sigmoid Linear Unit (SiLU) or swish function. * https://en.wikipedia.org/wiki/Rectifier_(neural_networks) * https://en.wikipedia.org/wiki/Swish_function The function takes a vector x of K real numbers as input and returns x * sigmoid(x). Swish is a smooth, non-mon...
2,362
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\back_propagation_neural_network.py
python
Python
#!/usr/bin/python """ A Framework of Back Propagation Neural Network (BP) model Easy to use: * add many layers as you want ! ! ! * clearly see how the loss decreasing Easy to expand: * more activation functions * more loss functions * more optimization method Author: Stephen Lee Github : https:/...
6,304
204
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\convolution_neural_network.py
python
Python
""" - - - - - -- - - - - - - - - - - - - - - - - - - - - - - Name - - CNN - Convolution Neural Network For Photo Recognizing Goal - - Recognize Handwriting Word Photo Detail: Total 5 layers neural network * Convolution layer * Pooling layer * Input layer layer of BP * Hidden layer of BP...
14,650
358
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\input_data.py
python
Python
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
12,353
343
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\simple_neural_network.py
python
Python
""" Forward propagation explanation: https://towardsdatascience.com/forward-propagation-in-neural-networks-simplified-math-and-code-version-bbcfef6f9250 """ import math import random # Sigmoid def sigmoid_function(value: float, deriv: bool = False) -> float: """Return the sigmoid function of a float. >>> si...
1,676
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
neural_network\two_hidden_layers_neural_network.py
python
Python
""" References: - http://neuralnetworksanddeeplearning.com/chap2.html (Backpropagation) - https://en.wikipedia.org/wiki/Sigmoid_function (Sigmoid activation function) - https://en.wikipedia.org/wiki/Feedforward_neural_network (Feedforward) """ import numpy as np class TwoHiddenLayerNeuralNetwork: def...
11,922
297
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\activity_selection.py
python
Python
"""The following implementation assumes that the activities are already sorted according to their finish time""" """Prints a maximum set of activities that can be done by a single person, one at a time""" # n --> Total number of activities # start[]--> An array that contains start time of all activities # finish[] -->...
1,296
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\alternative_list_arrange.py
python
Python
def alternative_list_arrange(first_input_list: list, second_input_list: list) -> list: """ The method arranges two lists as one list in alternative forms of the list elements. :param first_input_list: :param second_input_list: :return: List >>> alternative_list_arrange([1, 2, 3, 4, 5], ["A", "B"...
1,405
35
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\bankers_algorithm.py
python
Python
# A Python implementation of the Banker's Algorithm in Operating Systems using # Processes and Resources # { # "Author: "Biney Kingsley (bluedistro@github.io), bineykingsley36@gmail.com", # "Date": 28-10-2018 # } """ The Banker's algorithm is a resource allocation and deadlock avoidance algorithm developed by Edsger Di...
8,788
229
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\davis_putnam_logemann_loveland.py
python
Python
#!/usr/bin/env python3 """ Davis-Putnam-Logemann-Loveland (DPLL) algorithm is a complete, backtracking-based search algorithm for deciding the satisfiability of propositional logic formulae in conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiability (CNF-SAT) problem. For more information ...
12,083
368
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\doomsday.py
python
Python
#!/bin/python3 # Doomsday algorithm info: https://en.wikipedia.org/wiki/Doomsday_rule DOOMSDAY_LEAP = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] DOOMSDAY_NOT_LEAP = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] WEEK_DAY_NAMES = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Frida...
1,624
60
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\fischer_yates_shuffle.py
python
Python
#!/usr/bin/python """ The Fisher-Yates shuffle is an algorithm for generating a random permutation of a finite sequence. For more details visit wikipedia/Fischer-Yates-Shuffle. """ import random from typing import Any def fisher_yates_shuffle(data: list) -> list[Any]: for _ in range(len(data)): a = rando...
754
27
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\gauss_easter.py
python
Python
""" https://en.wikipedia.org/wiki/Computus#Gauss'_Easter_algorithm """ import math from datetime import UTC, datetime, timedelta def gauss_easter(year: int) -> datetime: """ Calculation Gregorian easter date for given year >>> gauss_easter(2007) datetime.datetime(2007, 4, 8, 0, 0, tzinfo=datetime.ti...
2,048
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\graham_scan.py
python
Python
""" This is a pure Python implementation of the Graham scan algorithm Source: https://en.wikipedia.org/wiki/Graham_scan For doctests run following command: python3 -m doctest -v graham_scan.py """ from __future__ import annotations from collections import deque from enum import Enum from math import atan2, degrees f...
5,602
173
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\greedy.py
python
Python
class Things: def __init__(self, name, value, weight): self.name = name self.value = value self.weight = weight def __repr__(self): return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})" def get_value(self): return self.value def get_name...
2,033
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\guess_the_number_search.py
python
Python
""" guess the number using lower,higher and the value to find or guess solution works by dividing lower and higher of number guessed suppose lower is 0, higher is 1000 and the number to guess is 355 >>> guess_the_number(10, 1000, 17) started... guess the number : 17 details : [505, 257, 133, 71, 40, 25, 17] """ d...
4,464
166
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\h_index.py
python
Python
""" Task: Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index. According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the...
1,914
72
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\least_recently_used.py
python
Python
from __future__ import annotations import sys from collections import deque from typing import TypeVar T = TypeVar("T") class LRUCache[T]: """ Page Replacement Algorithm, Least Recently Used (LRU) Caching. >>> lru_cache: LRUCache[str | int] = LRUCache(4) >>> lru_cache.refer("A") >>> lru_cache.r...
2,491
93
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\lfu_cache.py
python
Python
from __future__ import annotations from collections.abc import Callable from typing import TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode[T, U]: """ Double Linked List Node built specifically for LFU Cache >>> node = DoubleLinkedListNode(1,1) >>> node Node: key: 1, val: 1,...
10,092
320
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\linear_congruential_generator.py
python
Python
__author__ = "Tobias Carryer" from time import time class LinearCongruentialGenerator: """ A pseudorandom number generator. """ # The default value for **seed** is the result of a function call, which is not # normally recommended and causes ruff to raise a B008 error. However, in this case, ...
1,516
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\lru_cache.py
python
Python
from __future__ import annotations from collections.abc import Callable from typing import TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode[T, U]: """ Double Linked List Node built specifically for LRU Cache >>> DoubleLinkedListNode(1,1) Node: key: 1, val: 1, has next: False, ha...
10,452
337
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\magicdiamondpattern.py
python
Python
# Python program for generating diamond pattern in Python 3.7+ # Function to print upper half of diamond (pyramid) def floyd(n): """ Print the upper half of a diamond pattern with '*' characters. Args: n (int): Size of the pattern. Examples: >>> floyd(3) ' * \\n * * \\n* * *...
2,047
80
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\majority_vote_algorithm.py
python
Python
""" This is Booyer-Moore Majority Vote Algorithm. The problem statement goes like this: Given an integer array of size n, find all elements that appear more than ⌊ n/k ⌋ times. We have to solve in O(n) time and O(1) Space. URL : https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm """ from collect...
1,271
39
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\maximum_subsequence.py
python
Python
from collections.abc import Sequence def max_subsequence_sum(nums: Sequence[int] | None = None) -> int: """Return the maximum possible sum amongst all non - empty subsequences. Raises: ValueError: when nums is empty. >>> max_subsequence_sum([1,2,3,4,-2]) 10 >>> max_subsequence_sum([-2, -3,...
1,177
43
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\nested_brackets.py
python
Python
""" The nested brackets problem is a problem that determines if a sequence of brackets are properly nested. A sequence of brackets s is considered properly nested if any of the following conditions are true: - s is empty - s has the form (U) or [U] or {U} where U is a properly nested string - s has the fo...
1,948
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\number_container_system.py
python
Python
""" A number container system that uses binary search to delete and insert values into arrays with O(log n) write times and O(1) read times. This container system holds integers at indexes. Further explained in this leetcode problem > https://leetcode.com/problems/minimum-cost-tree-from-leaf-values """ class Number...
6,476
181
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\password.py
python
Python
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def password_generator(length: int = 8) -> str: """ Password Generator allows you to generate a random password of length N. >>> len(password_generator()) 8 >>> len(pa...
3,177
98
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\quine.py
python
Python
#!/bin/python3 # ruff: noqa: PLC3002 """ Quine: A quine is a computer program which takes no input and produces a copy of its own source code as its only output (disregarding this docstring and the shebang). More info on: https://en.wikipedia.org/wiki/Quine_(computing) """ print((lambda quine: quine % quine)("print(...
371
13
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\scoring_algorithm.py
python
Python
""" | developed by: markmelnic | original repo: https://github.com/markmelnic/Scoring-Algorithm Analyse data using a range based percentual proximity algorithm and calculate the linear maximum likelihood estimation. The basic principle is that all values supplied will be broken down to a range from ``0`` to ``1`` and ...
3,801
120
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\sdes.py
python
Python
def apply_table(inp, table): """ >>> apply_table("0123456789", list(range(10))) '9012345678' >>> apply_table("0123456789", list(range(9, -1, -1))) '8765432109' """ res = "" for i in table: res += inp[i - 1] return res def left_shift(data): """ >>> left_shift("012345...
2,703
97
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\sliding_window_maximum.py
python
Python
from collections import deque def sliding_window_maximum(numbers: list[int], window_size: int) -> list[int]: """ Return a list containing the maximum of each sliding window of size window_size. This implementation uses a monotonic deque to achieve O(n) time complexity. Args: numbers: List of...
1,905
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\tower_of_hanoi.py
python
Python
def move_tower(height, from_pole, to_pole, with_pole): """ >>> move_tower(3, 'A', 'B', 'C') moving disk from A to B moving disk from A to C moving disk from B to C moving disk from A to B moving disk from C to A moving disk from C to B moving disk from A to B """ if height >=...
728
29
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
other\word_search.py
python
Python
""" Creates a random wordsearch with eight different directions that are best described as compass locations. @ https://en.wikipedia.org/wiki/Word_search """ from random import choice, randint, shuffle # The words to display on the word search - # can be made dynamic by randonly selecting a certain number of # words...
15,507
396
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
physics\altitude_pressure.py
python
Python
""" Title : Calculate altitude using Pressure Description : The below algorithm approximates the altitude using Barometric formula """ def get_altitude_at_pressure(pressure: float) -> float: """ This method calculates the altitude from Pressure wrt to Sea level pressure as reference .Pressure is in...
1,590
53
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
physics\archimedes_principle_of_buoyant_force.py
python
Python
""" Calculate the buoyant force of any body completely or partially submerged in a static fluid. This principle was discovered by the Greek mathematician Archimedes. Equation for calculating buoyant force: Fb = p * V * g https://en.wikipedia.org/wiki/Archimedes%27_principle """ # Acceleration Constant on Earth (uni...
1,999
63