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
audio_filters\butterworth_filter.py
python
Python
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter """ Create 2nd-order IIR filters with Butterworth design. Code based on https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html Alternatively you can use scipy.signal.butter, which should yield the same results. """ def...
6,223
235
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
audio_filters\iir_filter.py
python
Python
from __future__ import annotations class IIRFilter: r""" N-Order IIR filter Assumes working with float samples normalized on [-1, 1] --- Implementation details: Based on the 2nd-order function from https://en.wikipedia.org/wiki/Digital_biquad_filter, this generalized N-order function...
3,371
101
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
audio_filters\README.md
readme
Markdown
# Audio Filter Audio filters work on the frequency of an audio signal to attenuate unwanted frequency and amplify wanted ones. They are used within anything related to sound, whether it is radio communication or a hi-fi system. * <https://www.masteringbox.com/filter-types/> * <http://ethanwiner.com/filters.html> * <h...
424
10
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
audio_filters\show_response.py
python
Python
from __future__ import annotations from abc import abstractmethod from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class FilterType(Protocol): @abstractmethod def process(self, sample: float) -> float: """ Calculate y[n] >>> issubcla...
2,572
96
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\all_combinations.py
python
Python
""" In this problem, we want to determine all possible combinations of k numbers out of 1 ... n. We use backtracking to solve this problem. Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))), """ from __future__ import annotations from itertools import combinations def combination_lists(n:...
3,597
117
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\all_permutations.py
python
Python
""" In this problem, we want to determine all possible permutations of the given sequence. We use backtracking to solve this problem. Time complexity: O(n! * n), where n denotes the length of the given sequence. """ from __future__ import annotations def generate_all_permutations(sequence: list[int | str]) -> None:...
2,600
89
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\all_subsequences.py
python
Python
""" In this problem, we want to determine all possible subsequences of the given sequence. We use backtracking to solve this problem. Time complexity: O(2^n), where n denotes the length of the given sequence. """ from __future__ import annotations from typing import Any def generate_all_subsequences(sequence: list...
2,304
94
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\coloring.py
python
Python
""" Graph Coloring also called "m coloring problem" consists of coloring a given graph with at most m colors such that no adjacent vertices are assigned the same color Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring """ def valid_coloring( neighbours: list[int], colored_vertices: list[int], color: int ) ...
3,571
122
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\combination_sum.py
python
Python
""" In the Combination Sum problem, we are given a list consisting of distinct integers. We need to find all the combinations whose sum equals to target given. We can use an element more than one. Time complexity(Average Case): O(n!) Constraints: 1 <= candidates.length <= 30 2 <= candidates[i] <= 40 All elements of c...
2,346
77
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\crossword_puzzle_solver.py
python
Python
# https://www.geeksforgeeks.org/solve-crossword-puzzle/ def is_valid( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> bool: """ Check if a word can be placed at the given position. >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', ...
3,821
132
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\generate_parentheses.py
python
Python
""" author: Aayush Soni Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Input: n = 2 Output: ["(())","()()"] Leetcode link: https://leetcode.com/problems/generate-parentheses/description/ """ def backtrack( partial: str, open_count: int, close_count: int, n:...
2,519
82
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\generate_parentheses_iterative.py
python
Python
def generate_parentheses_iterative(length: int) -> list[str]: """ Generate all valid combinations of parentheses (Iterative Approach). The algorithm works as follows: 1. Initialize an empty list to store the combinations. 2. Initialize a stack to keep track of partial combinations. 3. Start wit...
2,231
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\hamiltonian_cycle.py
python
Python
""" A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle through a graph that visits each node exactly once. Determining whether such paths and cycles exist in graphs is the 'Hamiltonian path problem', which is NP-complete. Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path """ def valid_connection( ...
6,011
177
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\knight_tour.py
python
Python
# Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM from __future__ import annotations def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]: """ Find all the valid positions a knight can move to from the current position. >>> get_valid_pos((1, 3), 4) [(2, 1), (0...
2,552
102
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\match_word_pattern.py
python
Python
def match_word_pattern(pattern: str, input_string: str) -> bool: """ Determine if a given pattern matches a string using backtracking. pattern: The pattern to match. input_string: The string to match against the pattern. return: True if the pattern matches the string, False otherwise. >>> matc...
1,867
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\minimax.py
python
Python
""" Minimax helps to achieve maximum score in a game by checking all possible moves depth is current depth in game tree. nodeIndex is index of current node in scores[]. if move is of maximizer return true else false leaves of game tree is stored in scores[] height is maximum height of Game tree """ from __future__ im...
3,152
96
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\n_queens.py
python
Python
""" The nqueens problem is of placing N queens on a N * N chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. """ from __future__ import annotations solution = [] def is_safe(bo...
3,402
110
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\n_queens_math.py
python
Python
r""" Problem: The n queens problem is: placing N queens on a N * N chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. Solution: To solve this problem we will use simple math. Fir...
5,095
159
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\power_sum.py
python
Python
""" Problem source: https://www.hackerrank.com/challenges/the-power-sum/problem Find the number of ways that a given integer X, can be expressed as the sum of the Nth powers of unique, natural numbers. For example, if X=13 and N=2. We have to find all combinations of unique squares adding up to 13. The only solution is...
2,715
92
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\rat_in_maze.py
python
Python
from __future__ import annotations def solve_maze( maze: list[list[int]], source_row: int, source_column: int, destination_row: int, destination_column: int, ) -> list[list[int]]: """ This method solves the "rat in maze" problem. Parameters : - maze: A two dimensional matrix of...
6,760
198
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\README.md
readme
Markdown
# Backtracking Backtracking is a way to speed up the search process by removing candidates when they can't be the solution of a problem. * <https://en.wikipedia.org/wiki/Backtracking> * <https://en.wikipedia.org/wiki/Decision_tree_pruning> * <https://medium.com/@priyankmistry1999/backtracking-sudoku-6e4439e4825c> * <...
382
9
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\sudoku.py
python
Python
""" Given a partially filled 9x9 2D array, the objective is to fill a 9x9 square grid with digits numbered 1 to 9, so that every row, column, and and each of the nine 3x3 sub-grids contains all of the digits. This can be solved using Backtracking and is similar to n-queens. We check to see if a cell is safe or not and...
4,091
134
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\sum_of_subsets.py
python
Python
""" The sum-of-subsets problem states that a set of non-negative integers, and a value M, determine all possible subsets of the given set whose summation sum equal to given M. Summation of the chosen numbers must be equal to given number M and one number can be used only once. """ def generate_sum_of_subsets_solutio...
2,289
82
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\word_break.py
python
Python
""" Word Break Problem is a well-known problem in computer science. Given a string and a dictionary of words, the task is to determine if the string can be segmented into a sequence of one or more dictionary words. Wikipedia: https://en.wikipedia.org/wiki/Word_break_problem """ def backtrack(input_string: str, word_...
2,220
75
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\word_ladder.py
python
Python
""" Word Ladder is a classic problem in computer science. The problem is to transform a start word into an end word by changing one letter at a time. Each intermediate word must be a valid word from a given list of words. The goal is to find a transformation sequence from the start word to the end word. Wikipedia: htt...
3,828
101
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
backtracking\word_search.py
python
Python
""" Author : Alexander Pantyukhin Date : November 24, 2022 Task: Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same let...
4,588
163
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\binary_and_operator.py
python
Python
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_and(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary and operation on the integers provided. >>> binary_and(25, 32) '0b000000' >>>...
1,462
53
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\binary_coded_decimal.py
python
Python
def binary_coded_decimal(number: int) -> str: """ Find binary coded decimal (bcd) of integer base 10. Each digit of the number is represented by a 4-bit binary. Example: >>> binary_coded_decimal(-2) '0b0000' >>> binary_coded_decimal(-1) '0b0000' >>> binary_coded_decimal(0) '0b000...
734
30
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\binary_count_setbits.py
python
Python
def binary_count_setbits(a: int) -> int: """ Take in 1 integer, return a number that is the number of 1's in binary representation of that number. >>> binary_count_setbits(25) 3 >>> binary_count_setbits(36) 2 >>> binary_count_setbits(16) 1 >>> binary_count_setbits(58) 4 ...
1,151
42
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\binary_count_trailing_zeros.py
python
Python
from math import log2 def binary_count_trailing_zeros(a: int) -> int: """ Take in 1 integer, return a number that is the number of trailing zeros in binary representation of that number. >>> binary_count_trailing_zeros(25) 0 >>> binary_count_trailing_zeros(36) 2 >>> binary_count_trail...
1,278
45
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\binary_or_operator.py
python
Python
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_or(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, and return a binary number that is the result of a binary or operation on the integers provided. >>> binary_or(25, 32) '0b111001' >>> bi...
1,462
49
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\binary_shifts.py
python
Python
# Information on binary shifts: # https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types # https://www.interviewcake.com/concept/java/bit-shift def logical_left_shift(number: int, shift_amount: int) -> str: """ Take in 2 positive integers. 'number' is the integer to be logical...
3,512
110
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\binary_twos_complement.py
python
Python
# Information on 2's complement: https://en.wikipedia.org/wiki/Two%27s_complement def twos_complement(number: int) -> str: """ Take in a negative integer 'number'. Return the two's complement representation of 'number'. >>> twos_complement(0) '0b0' >>> twos_complement(-1) '0b11' >>> t...
1,164
44
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\binary_xor_operator.py
python
Python
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_xor(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>>...
1,502
53
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\bitwise_addition_recursive.py
python
Python
""" Calculates the sum of two non-negative integers using bitwise operators Wikipedia explanation: https://en.wikipedia.org/wiki/Binary_number """ def bitwise_addition_recursive(number: int, other_number: int) -> int: """ >>> bitwise_addition_recursive(4, 5) 9 >>> bitwise_addition_recursive(8, 9) ...
1,649
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\count_1s_brian_kernighan_method.py
python
Python
def get_1s_count(number: int) -> int: """ Count the number of set bits in a 32 bit integer using Brian Kernighan's way. Ref - https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan >>> get_1s_count(25) 3 >>> get_1s_count(37) 3 >>> get_1s_count(21) 3 >>> get_1s...
1,332
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\count_number_of_one_bits.py
python
Python
from timeit import timeit def get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int: """ Count the number of set bits in a 32 bit integer >>> get_set_bits_count_using_brian_kernighans_algorithm(25) 3 >>> get_set_bits_count_using_brian_kernighans_algorithm(37) 3 >>> get_se...
2,925
94
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\excess_3_code.py
python
Python
def excess_3_code(number: int) -> str: """ Find excess-3 code of integer base 10. Add 3 to all digits in a decimal number then convert to a binary-coded decimal. https://en.wikipedia.org/wiki/Excess-3 >>> excess_3_code(0) '0b0011' >>> excess_3_code(3) '0b0110' >>> excess_3_code(2) ...
655
28
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\find_previous_power_of_two.py
python
Python
def find_previous_power_of_two(number: int) -> int: """ Find the largest power of two that is less than or equal to a given integer. https://stackoverflow.com/questions/1322510 >>> [find_previous_power_of_two(i) for i in range(18)] [0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16] >>> fi...
997
31
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\find_unique_number.py
python
Python
def find_unique_number(arr: list[int]) -> int: """ Given a list of integers where every element appears twice except for one, this function returns the element that appears only once using bitwise XOR. >>> find_unique_number([1, 1, 2, 2, 3]) 3 >>> find_unique_number([4, 5, 4, 6, 6]) 5 >...
1,035
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\gray_code_sequence.py
python
Python
def gray_code(bit_count: int) -> list: """ Takes in an integer n and returns a n-bit gray code sequence An n-bit gray code sequence is a sequence of 2^n integers where: a) Every integer is between [0,2^n -1] inclusive b) The sequence begins with 0 c) An integer appears at most one times...
2,538
95
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\highest_set_bit.py
python
Python
def get_highest_set_bit_position(number: int) -> int: """ Returns position of the highest set bit of a number. Ref - https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious >>> get_highest_set_bit_position(25) 5 >>> get_highest_set_bit_position(37) 6 >>> get_highest_set_bi...
884
35
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\index_of_rightmost_set_bit.py
python
Python
# Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/ def get_index_of_rightmost_set_bit(number: int) -> int: """ Take in a positive integer 'number'. Returns the zero-based index of first set bit in that 'number' from right. Returns -1, If no set bit found. >>> get_index_of_r...
1,534
52
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\is_even.py
python
Python
def is_even(number: int) -> bool: """ return true if the input integer is even Explanation: Lets take a look at the following decimal to binary conversions 2 => 10 14 => 1110 100 => 1100100 3 => 11 13 => 1101 101 => 1100101 from the above examples we can observe that for all ...
871
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\is_power_of_two.py
python
Python
""" Author : Alexander Pantyukhin Date : November 1, 2022 Task: Given a positive int number. Return True if this number is power of 2 or False otherwise. Implementation notes: Use bit manipulation. For example if the number is the power of two it's bits representation: n = 0..100..00 n - 1 = 0..011..11 n & (...
1,367
58
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\largest_pow_of_two_le_num.py
python
Python
""" Author : Naman Sharma Date : October 2, 2023 Task: To Find the largest power of 2 less than or equal to a given number. Implementation notes: Use bit manipulation. We start from 1 & left shift the set bit to check if (res<<1)<=number. Each left bit shift represents a pow of 2. For example: number: 15 res: ...
1,392
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\missing_number.py
python
Python
def find_missing_number(nums: list[int]) -> int: """ Finds the missing number in a list of consecutive integers. Args: nums: A list of integers. Returns: The missing number. Example: >>> find_missing_number([0, 1, 3, 4]) 2 >>> find_missing_number([4, 3, 1, ...
921
41
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\numbers_different_signs.py
python
Python
""" Author : Alexander Pantyukhin Date : November 30, 2022 Task: Given two int numbers. Return True these numbers have opposite signs or False otherwise. Implementation notes: Use bit manipulation. Use XOR for two numbers. """ def different_signs(num1: int, num2: int) -> bool: """ Return True if numbers...
895
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\power_of_4.py
python
Python
""" Task: Given a positive int number. Return True if this number is power of 4 or False otherwise. Implementation notes: Use bit manipulation. For example if the number is the power of 2 it's bits representation: n = 0..100..00 n - 1 = 0..011..11 n & (n - 1) - no intersections = 0 If the number is a power of 4 ...
1,560
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\README.md
readme
Markdown
# Bit manipulation Bit manipulation is the act of manipulating bits to detect errors (hamming code), encrypts and decrypts messages (more on that in the 'ciphers' folder) or just do anything at the lowest level of your computer. * <https://en.wikipedia.org/wiki/Bit_manipulation> * <https://docs.python.org/3/reference...
733
12
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\reverse_bits.py
python
Python
def get_reverse_bit_string(number: int) -> str: """ Return the reverse bit string of a 32 bit integer >>> get_reverse_bit_string(9) '10010000000000000000000000000000' >>> get_reverse_bit_string(43) '11010100000000000000000000000000' >>> get_reverse_bit_string(2873) '10011100110100000000...
2,414
87
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\single_bit_manipulation_operations.py
python
Python
#!/usr/bin/env python3 """Provide the functionality to manipulate a single bit.""" def set_bit(number: int, position: int) -> int: """ Set the bit at position to 1. Details: perform bitwise or for given number and X. Where X is a number with all the bits - zeroes and bit on given position - one....
2,404
101
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
bit_manipulation\swap_all_odd_and_even_bits.py
python
Python
def show_bits(before: int, after: int) -> str: """ >>> print(show_bits(0, 0xFFFF)) 0: 00000000 65535: 1111111111111111 """ return f"{before:>5}: {before:08b}\n{after:>5}: {after:08b}" def swap_odd_even_bits(num: int) -> int: """ 1. We use bitwise AND operations to separate the even...
1,951
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
blockchain\diophantine_equation.py
python
Python
from __future__ import annotations from maths.greatest_common_divisor import greatest_common_divisor def diophantine(a: int, b: int, c: int) -> tuple[float, float]: """ Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the diophantine equation a*x + b*y = c has a solution (wher...
2,850
110
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
blockchain\README.md
readme
Markdown
# Blockchain A Blockchain is a type of **distributed ledger** technology (DLT) that consists of a growing list of records, called **blocks**, that are securely linked together using **cryptography**. Let's break down the terminologies in the above definition. We find below terminologies, - Digital Ledger Technology ...
3,763
46
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\and_gate.py
python
Python
""" 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 | ...
1,139
51
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\imply_gate.py
python
Python
""" 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 | ...
2,553
92
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\karnaugh_map_simplification.py
python
Python
""" 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" >...
1,424
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\multiplexer.py
python
Python
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...
1,266
43
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\nand_gate.py
python
Python
""" 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 | ---------------...
952
37
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\nimply_gate.py
python
Python
""" 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 ...
1,004
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\nor_gate.py
python
Python
""" 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 ...
1,792
69
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\not_gate.py
python
Python
""" 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 ...
706
31
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\or_gate.py
python
Python
""" 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 | | ...
887
36
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\quine_mc_cluskey.py
python
Python
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...
4,439
164
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\README.md
readme
Markdown
# Boolean Algebra Boolean algebra is used to do arithmetic with bits of values True (1) or False (0). There are three basic operations: 'and', 'or' and 'not'. * <https://en.wikipedia.org/wiki/Boolean_algebra> * <https://plato.stanford.edu/entries/boolalg-math/>
271
8
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\xnor_gate.py
python
Python
""" 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 | -...
966
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
boolean_algebra\xor_gate.py
python
Python
""" 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...
924
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
cellular_automata\conways_game_of_life.py
python
Python
""" Conway's Game of Life implemented in Python. https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life """ from __future__ import annotations from PIL import Image # Define glider example GLIDER = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]...
3,259
97
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
cellular_automata\game_of_life.py
python
Python
"""Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) Requirements: - numpy - random - time - matplotlib Python: - 3.5 Usage: - $python3 game_of_life <canvas_size:int> Game-Of-Life Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-popul...
3,156
130
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
cellular_automata\langtons_ant.py
python
Python
""" Langton's ant @ https://en.wikipedia.org/wiki/Langton%27s_ant @ https://upload.wikimedia.org/wikipedia/commons/0/09/LangtonsAntAnimated.gif """ from functools import partial from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation WIDTH = 80 HEIGHT = 80 class LangtonsAnt: """ ...
3,546
107
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
cellular_automata\nagel_schrekenberg.py
python
Python
""" Simulate the evolution of a highway with only one road that is a loop. The highway is divided in cells, each cell can have at most one car in it. The highway is a loop so when a car comes to one end, it will come out on the other. Each car is represented by its speed (from 0 to 5). Some information about speed: ...
5,315
141
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
cellular_automata\one_dimensional.py
python
Python
""" Return an image of 16 generations of one-dimensional cellular automata based on a given ruleset number https://mathworld.wolfram.com/ElementaryCellularAutomaton.html """ from __future__ import annotations from PIL import Image # Define the first generation of cells # fmt: off CELLS = [[0, 0, 0, 0, 0, 0, 0, 0, 0,...
2,442
75
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
cellular_automata\README.md
readme
Markdown
# Cellular Automata Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell. They usually follow simple rules but can lead to the creation of complex forms. The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). ...
449
9
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
cellular_automata\wa_tor.py
python
Python
""" Wa-Tor algorithm (1984) | @ https://en.wikipedia.org/wiki/Wa-Tor | @ https://beltoforion.de/en/wator/ | @ https://beltoforion.de/en/wator/images/wator_medium.webm This solution aims to completely remove any systematic approach to the Wa-Tor planet, and utilise fully random methods. The constants are a working se...
21,104
549
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\a1z26.py
python
Python
""" Convert a string of characters to a sequence of numbers corresponding to the character's position in the alphabet. https://www.dcode.fr/letter-number-cipher http://bestcodes.weebly.com/a1z26.html """ from __future__ import annotations def encode(plain: str) -> list[int]: """ >>> encode("myname") [13...
777
36
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\affine_cipher.py
python
Python
import random import sys from maths.greatest_common_divisor import gcd_by_iterative from . import cryptomath_module as cryptomath SYMBOLS = ( r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`""" r"""abcdefghijklmnopqrstuvwxyz{|}~""" ) def check_keys(key_a: int, key_b: int, mode: str) ->...
3,566
110
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\atbash.py
python
Python
"""https://en.wikipedia.org/wiki/Atbash""" import string def atbash_slow(sequence: str) -> str: """ >>> atbash_slow("ABCDEFG") 'ZYXWVUT' >>> atbash_slow("aW;;123BX") 'zD;;123YC' """ output = "" for i in sequence: extract = ord(i) if 65 <= extract <= 90: ou...
1,502
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\autokey.py
python
Python
""" https://en.wikipedia.org/wiki/Autokey_cipher An autokey cipher (also known as the autoclave cipher) is a cipher that incorporates the message (the plaintext) into the key. The key is generated from the message in some automated fashion, sometimes by selecting certain letters from the text or, more commonly, by add...
4,900
151
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\baconian_cipher.py
python
Python
""" Program to encode and decode Baconian or Bacon's Cipher Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher """ encode_dict = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j":...
2,225
90
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\base16.py
python
Python
def base16_encode(data: bytes) -> str: """ Encodes the given bytes into base16. >>> base16_encode(b'Hello World!') '48656C6C6F20576F726C6421' >>> base16_encode(b'HELLO WORLD!') '48454C4C4F20574F524C4421' >>> base16_encode(b'') '' """ # Turn the data into a list of integers (wher...
2,384
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\base32.py
python
Python
""" Base32 encoding and decoding https://en.wikipedia.org/wiki/Base32 """ B32_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" def base32_encode(data: bytes) -> bytes: """ >>> base32_encode(b"Hello World!") b'JBSWY3DPEBLW64TMMQQQ====' >>> base32_encode(b"123456") b'GEZDGNBVGY======' >>> base32_e...
1,472
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\base64_cipher.py
python
Python
B64_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def base64_encode(data: bytes) -> bytes: """Encodes data according to RFC4648. The data is first transformed to binary and appended with binary digits so that its length becomes a multiple of 6, then each 6 binary digits wil...
5,178
143
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\base85.py
python
Python
""" Base85 (Ascii85) encoding and decoding https://en.wikipedia.org/wiki/Ascii85 """ def _base10_to_85(d: int) -> str: return "".join(chr(d % 85 + 33)) + _base10_to_85(d // 85) if d > 0 else "" def _base85_to_10(digits: list) -> int: return sum(char * 85**i for i, char in enumerate(reversed(digits))) def...
1,925
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\beaufort_cipher.py
python
Python
""" Author: Mohit Radadiya """ from string import ascii_uppercase dict1 = {char: i for i, char in enumerate(ascii_uppercase)} dict2 = dict(enumerate(ascii_uppercase)) # This function generates the key in # a cyclic manner until it's length isn't # equal to the length of original text def generate_key(message: str, ...
2,022
83
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\bifid.py
python
Python
#!/usr/bin/env python3 """ The Bifid Cipher uses a Polybius Square to encipher a message in a way that makes it fairly difficult to decipher without knowing the secret. https://www.braingle.com/brainteasers/codes/bifid.php """ import numpy as np SQUARE = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"...
3,695
112
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\brute_force_caesar_cipher.py
python
Python
import string def decrypt(message: str) -> None: """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryptio...
2,020
59
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\caesar_cipher.py
python
Python
from __future__ import annotations from string import ascii_letters def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str: """ encrypt ======= Encodes a given string with the caesar cipher and returns the encoded message Parameters: ----------- * `input_str...
8,212
257
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\cryptomath_module.py
python
Python
from maths.greatest_common_divisor import gcd_by_iterative def find_mod_inverse(a: int, m: int) -> int: if gcd_by_iterative(a, m) != 1: msg = f"mod inverse of {a!r} and {m!r} does not exist" raise ValueError(msg) u1, u2, u3 = 1, 0, a v1, v2, v3 = 0, 1, m while v3 != 0: q = u3 /...
445
14
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\decrypt_caesar_with_chi_squared.py
python
Python
#!/usr/bin/env python3 from __future__ import annotations def decrypt_caesar_with_chi_squared( ciphertext: str, cipher_alphabet: list[str] | None = None, frequencies_dict: dict[str, float] | None = None, case_sensitive: bool = False, ) -> tuple[int, float, str]: """ Basic Usage ===========...
9,788
254
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\deterministic_miller_rabin.py
python
Python
"""Created by Nathan Damon, @bizzfitch on github >>> test_miller_rabin() """ def miller_rabin(n: int, allow_probable: bool = False) -> bool: """Deterministic Miller-Rabin algorithm for primes ~< 3.32e24. Uses numerical analysis results to return whether or not the passed number is prime. If the passed nu...
4,319
138
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\diffie.py
python
Python
from __future__ import annotations def find_primitive(modulus: int) -> int | None: """ Find a primitive root modulo modulus, if one exists. Args: modulus : The modulus for which to find a primitive root. Returns: The primitive root if one exists, or None if there is none. Exampl...
1,584
54
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\diffie_hellman.py
python
Python
from binascii import hexlify from hashlib import sha256 from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 primes = { # 1536-bit 5: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234...
12,414
268
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\elgamal_key_generator.py
python
Python
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller min_primitive_root = 3 # I have written my code naively same as definition of primitive root # however every time I run this program, memory exceeded... # so I used 4.80 Algorithm in # Handbook of Applied Cry...
2,234
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\enigma_machine2.py
python
Python
""" | Wikipedia: https://en.wikipedia.org/wiki/Enigma_machine | Video explanation: https://youtu.be/QwQVMqfoB2E | Also check out Numberphile's and Computerphile's videos on this topic This module contains function ``enigma`` which emulates the famous Enigma machine from WWII. Module includes: - ``enigma`` function -...
9,234
302
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\fractionated_morse_cipher.py
python
Python
""" Python program for the Fractionated Morse Cipher. The Fractionated Morse cipher first converts the plaintext to Morse code, then enciphers fixed-size blocks of Morse code back to letters. This procedure means plaintext letters are mixed into the ciphertext letters, making it more secure than substitution ciphers. ...
4,171
169
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\gronsfeld_cipher.py
python
Python
from string import ascii_uppercase def gronsfeld(text: str, key: str) -> str: """ Encrypt plaintext with the Gronsfeld cipher >>> gronsfeld('hello', '412') 'LFNPP' >>> gronsfeld('hello', '123') 'IGOMQ' >>> gronsfeld('', '123') '' >>> gronsfeld('yes, ¥€$ - _!@#%?', '0') 'YES, ¥...
1,265
46
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\hill_cipher.py
python
Python
""" Hill Cipher: The 'HillCipher' class below implements the Hill Cipher algorithm which uses modern linear algebra techniques to encode and decode text using an encryption key matrix. Algorithm: Let the order of the encryption key be N (as it is a square matrix). Your text is divided into batches of length N and con...
7,522
222
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\mixed_keyword_cypher.py
python
Python
from string import ascii_uppercase def mixed_keyword( keyword: str, plaintext: str, verbose: bool = False, alphabet: str = ascii_uppercase ) -> str: """ For keyword: hello H E L O A B C D F G I J K M N P Q R S T U V W X Y Z and map vertically >>> mixed_keyword("colleg...
2,631
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
ciphers\mono_alphabetic_ciphers.py
python
Python
from typing import Literal LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def translate_message( key: str, message: str, mode: Literal["encrypt", "decrypt"] ) -> str: """ >>> translate_message("QWERTYUIOPASDFGHJKLZXCVBNM","Hello World","encrypt") 'Pcssi Bidsm' """ chars_a = LETTERS if mode == "decryp...
1,835
64