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
digital_image_processing\filters\sobel_filter.py
python
Python
# @Author : lightXu # @File : sobel_filter.py # @Time : 2019/7/8 0008 下午 16:26 import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from digital_image_processing.filters.convolve import img_convolve def sobel_filter(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, ...
1,196
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\histogram_equalization\histogram_stretch.py
python
Python
""" Created on Fri Sep 28 15:22:29 2018 @author: Binish125 """ import copy import os import cv2 import numpy as np from matplotlib import pyplot as plt class ConstantStretch: def __init__(self): self.img = "" self.original_image = "" self.last_list = [] self.rem = 0 self...
1,963
65
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\index_calculation.py
python
Python
# Author: João Gustavo A. Amorim # Author email: joaogustavoamorim@gmail.com # Coding date: jan 2019 # python/black: True # Imports import numpy as np # Class implemented to calculus the index class IndexCalculation: """ # Class Summary This algorithm consists in calculating vegetation indices, ...
20,264
576
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\morphological_operations\dilation_operation.py
python
Python
from pathlib import Path import numpy as np from PIL import Image def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: """ Return gray image from rgb image >>> rgb_to_gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb_to_gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb_to_gray(np...
2,625
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\morphological_operations\erosion_operation.py
python
Python
from pathlib import Path import numpy as np from PIL import Image def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: """ Return gray image from rgb image >>> rgb_to_gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb_to_gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb_to_gray(n...
2,681
83
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\resize\resize.py
python
Python
"""Multiple image resizing techniques""" import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: """ Simplest and fastest version of image resizing. Source: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation """ def __init__(self, img, dst_...
2,292
73
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\rotation\rotation.py
python
Python
from pathlib import Path import cv2 import numpy as np from matplotlib import pyplot as plt def get_rotation( img: np.ndarray, pt1: np.ndarray, pt2: np.ndarray, rows: int, cols: int ) -> np.ndarray: """ Get image rotation :param img: np.ndarray :param pt1: 3x2 list :param pt2: 3x2 list :p...
1,843
57
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\sepia.py
python
Python
""" Implemented an algorithm using opencv to tone an image with sepia technique """ from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): """ Function create sepia tone. Source: https://en.wikipedia.org/wiki/Sepia_(color) """ pixel_h, pixel_v = img.shape[0],...
1,475
52
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
digital_image_processing\test_digital_image_processing.py
test
Python
""" PyTest's for Digital Image Processing """ import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uint8 from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing...
4,301
135
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\closest_pair_of_points.py
python
Python
""" The algorithm finds distance between closest pair of points in the given n points. Approach used -> Divide and conquer The points are sorted based on Xco-ords and then based on Yco-ords separately. And by applying divide and conquer approach, minimum distance is obtained recursively. >> Closest points can lie on d...
4,397
142
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\convex_hull.py
python
Python
""" The convex hull problem is problem of finding all the vertices of convex polygon, P of a set of points in a plane such that all the points are either on the vertices of P or inside P. TH convex hull problem has several applications in geometrical problems, computer graphics and game development. Two algorithms hav...
16,738
508
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\heaps_algorithm.py
python
Python
""" Heap's algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implem...
1,591
57
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\heaps_algorithm_iterative.py
python
Python
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure p...
1,672
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\inversions.py
python
Python
""" Given an array-like data structure A[1..n], how many pairs (i, j) for all 1 <= i < j <= n such that A[i] > A[j]? These pairs are called inversions. Counting the number of such inversions in an array-like object is the important. Among other things, counting inversions can help us determine how close a given array i...
4,743
154
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\kth_order_statistic.py
python
Python
""" Find the kth smallest element in linear time using divide and conquer. Recall we can do this trivially in O(nlogn) time. Sort the list and access kth element in constant time. This is a divide and conquer algorithm that can find a solution in O(n) time. For more information of this algorithm: https://web.stanford...
1,822
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\max_difference_pair.py
python
Python
def max_difference(a: list[int]) -> tuple[int, int]: """ We are given an array A[1..n] of integers, n >= 1. We want to find a pair of indices (i, j) such that 1 <= i <= j <= n and A[j] - A[i] is as large as possible. Explanation: https://www.geeksforgeeks.org/maximum-difference-between-two-elem...
1,332
45
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\max_subarray.py
python
Python
""" The maximum subarray problem is the task of finding the continuous subarray that has the maximum sum within a given array of numbers. For example, given the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the contiguous subarray with the maximum sum is [4, -1, 2, 1], which has a sum of 6. This divide-and-conquer algorithm ...
3,601
114
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\mergesort.py
python
Python
from __future__ import annotations def merge(left_half: list, right_half: list) -> list: """Helper function for mergesort. >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [1,2,3] >>> right_half = [4,5,6] >>> merge(left_half, right_...
3,124
113
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\peak.py
python
Python
""" Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. (for p >= 1) An obvious solution can be performed in O(n), to find the maximum of the array. (From Kleinberg and Tardos. Algorithm Design. Addison Wesl...
1,306
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\power.py
python
Python
def actual_power(a: int, b: int) -> int: """ Function using divide and conquer to calculate a^b. It only works for integer a,b. :param a: The base of the power operation, an integer. :param b: The exponent of the power operation, a non-negative integer. :return: The result of a^b. Examples...
1,165
54
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
divide_and_conquer\strassen_matrix_multiplication.py
python
Python
from __future__ import annotations import math def default_matrix_multiplication(a: list, b: list) -> list: """ Multiplication only for 2x2 matrices """ if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2: raise Exception("Matrices are not 2x2") new_matrix = [ [a[0][...
6,246
173
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
docs\conf.py
python
Python
from sphinx_pyproject import SphinxConfig project = SphinxConfig("../pyproject.toml", globalns=globals()).name
115
4
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\abbreviation.py
python
Python
""" https://www.hackerrank.com/challenges/abbr/problem You can perform the following operation on some string, : 1. Capitalize zero or more of 's lowercase letters at some index i (i.e., make them uppercase). 2. Delete all of the remaining lowercase letters in . Example: a=daBcd and b="ABC" daBcd -> capitalize a a...
974
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\all_construct.py
python
Python
""" Program to list all the ways a target string can be constructed from the given list of substrings """ from __future__ import annotations def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]: """ returns the list containing all the possible combinations a string(`targe...
2,042
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\bitmask.py
python
Python
""" This is a Python implementation for questions involving task assignments between people. Here Bitmasking and DP are used for solving this. Question :- We have N tasks and M people. Each person in M can do only certain of these tasks. Also a person can do only one task and a task is performed only by one person. F...
3,214
90
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\catalan_numbers.py
python
Python
""" Print all the Catalan numbers from 0 to n, n being the user input. * The Catalan numbers are a sequence of positive integers that * appear in many counting problems in combinatorics [1]. Such * problems include counting [2]: * - The number of Dyck words of length 2n * - The number well-formed expressions with...
2,774
80
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\climbing_stairs.py
python
Python
#!/usr/bin/env python3 def climb_stairs(number_of_steps: int) -> int: """ LeetCdoe No.70: Climbing Stairs Distinct ways to climb a number_of_steps staircase where each time you can either climb 1 or 2 steps. Args: number_of_steps: number of steps on the staircase Returns: Dis...
1,156
43
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\combination_sum_iv.py
python
Python
""" Question: You are given an array of distinct integers and you have to tell how many different ways of selecting the elements from the array are there such that the sum of chosen elements is equal to the target number tar. Example Input: * N = 3 * target = 5 * array = [1, 2, 5] Output: ...
2,926
103
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\edit_distance.py
python
Python
""" Author : Turfa Auliarachman Date : October 12, 2016 This is a pure Python implementation of Dynamic Programming solution to the edit distance problem. The problem is : Given two strings A and B. Find the minimum number of operations to string B such that A = B. The permitted operations are removal, insertion...
3,538
104
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\factorial.py
python
Python
# Factorial of a number using memoization from functools import lru_cache @lru_cache def factorial(num: int) -> int: """ >>> factorial(7) 5040 >>> factorial(-1) Traceback (most recent call last): ... ValueError: Number should not be negative. >>> [factorial(i) for i in range(10)] ...
612
28
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\fast_fibonacci.py
python
Python
#!/usr/bin/env python3 """ This program calculates the nth Fibonacci number in O(log(n)). It's possible to calculate F(1_000_000) in less than a second. """ from __future__ import annotations import sys def fibonacci(n: int) -> int: """ return F(n) >>> [fibonacci(i) for i in range(13)] [0, 1, 1, 2,...
902
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\fibonacci.py
python
Python
""" This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem. """ class Fibonacci: def __init__(self) -> None: self.sequence = [0, 1] def get(self, index: int) -> list: """ Get the Fibonacci number of `index`. If the number does not exist,...
1,417
52
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\fizz_buzz.py
python
Python
# https://en.wikipedia.org/wiki/Fizz_buzz#Programming def fizz_buzz(number: int, iterations: int) -> str: """ | Plays FizzBuzz. | Prints Fizz if number is a multiple of ``3``. | Prints Buzz if its a multiple of ``5``. | Prints FizzBuzz if its a multiple of both ``3`` and ``5`` or ``15``. | Els...
2,044
66
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\floyd_warshall.py
python
Python
import math class Graph: def __init__(self, n=0): # a graph with Node 0,1,...,N-1 self.n = n self.w = [ [math.inf for j in range(n)] for i in range(n) ] # adjacency matrix for weight self.dp = [ [math.inf for j in range(n)] for i in range(n) ] # d...
2,262
86
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\integer_partition.py
python
Python
""" The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k into k parts. These two facts together are used for this alg...
1,822
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\iterating_through_submasks.py
python
Python
""" Author : Syed Faizan (3rd Year Student IIIT Pune) github : faizan2700 You are given a bitmask m and you want to efficiently iterate through all of its submasks. The mask s is submask of m if only bits that were included in bitmask are set """ from __future__ import annotations def list_of_submasks(mask: int) -> ...
1,809
63
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\k_means_clustering_tensorflow.py
python
Python
from random import shuffle import tensorflow as tf from numpy import array def tf_k_means_cluster(vectors, noofclusters): """ K-Means Clustering using TensorFlow. 'vectors' should be a n*k 2-D NumPy array, where n is the number of vectors of dimensionality k. 'noofclusters' should be an integer. ...
6,143
147
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\knapsack.py
python
Python
""" Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that only the integer weights 0-1 knapsack problem is solvable using dynamic programming. """ def mf_knapsack(i, wt, val, j): """ This code involves the concept of memory ...
5,325
154
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\largest_divisible_subset.py
python
Python
from __future__ import annotations def largest_divisible_subset(items: list[int]) -> list[int]: """ Algorithm to find the biggest subset in the given array such that for any 2 elements x and y in the subset, either x divides y or y divides x. >>> largest_divisible_subset([1, 16, 7, 8, 4]) [16, 8, ...
2,225
75
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\longest_common_subsequence.py
python
Python
""" LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily continuous. Example:"abc", "abg" are subsequences of "abcdefgh". """ def longest_common_subsequence(x: str, y: str):...
2,810
96
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\longest_common_substring.py
python
Python
""" Longest Common Substring Problem Statement: Given two sequences, find the longest common substring present in both of them. A substring is necessarily continuous. Example: ``abcdef`` and ``xabded`` have two longest common substrings, ``ab`` or ``de``. Therefore, algorithm should return any one ...
2,122
71
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\longest_increasing_subsequence.py
python
Python
""" Author : Mehdi ALAOUI This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence. The problem is: Given an array, to find the longest and increasing sub-array in that given array and return it. Example: ``[10, 22, 9, 33, 21, 50, 41,...
1,943
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\longest_increasing_subsequence_iterative.py
python
Python
""" Author : Sanjay Muthu <https://github.com/XenoBytesX> This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence. The problem is: Given an array, to find the longest and increasing sub-array in that given array and return it. Example: ...
2,255
73
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\longest_increasing_subsequence_o_nlogn.py
python
Python
############################# # Author: Aravind Kashyap # File: lis.py # comments: This programme outputs the Longest Strictly Increasing Subsequence in # O(NLogN) Where N is the Number of elements in the list ############################# from __future__ import annotations def ceil_index(v, left, right, ke...
1,445
56
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\longest_palindromic_subsequence.py
python
Python
""" author: Sanket Kittad Given a string s, find the longest palindromic subsequence's length in s. Input: s = "bbbab" Output: 4 Explanation: One possible longest palindromic subsequence is "bbbb". Leetcode link: https://leetcode.com/problems/longest-palindromic-subsequence/description/ """ def longest_palindromic_su...
1,300
45
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\matrix_chain_multiplication.py
python
Python
""" | Find the minimum number of multiplications needed to multiply chain of matrices. | Reference: https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/ The algorithm has interesting real-world applications. Example: 1. Image transformations in Computer Graphics as images are composed of matrix. 2. Sol...
5,011
152
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\matrix_chain_order.py
python
Python
import sys """ Dynamic Programming Implementation of Matrix Chain Multiplication Time Complexity: O(n^3) Space Complexity: O(n^2) Reference: https://en.wikipedia.org/wiki/Matrix_chain_multiplication """ def matrix_chain_order(array: list[int]) -> tuple[list[list[int]], list[list[int]]]: """ >>> matrix_chain...
1,925
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\max_non_adjacent_sum.py
python
Python
# Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo from __future__ import annotations def maximum_non_adjacent_sum(nums: list[int]) -> int: """ Find the maximum non-adjacent sum of the integers in the nums input list >>> maximum_non_adjacent_sum([1, 2, 3]) 4 >>> ma...
913
35
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\max_product_subarray.py
python
Python
def max_product_subarray(numbers: list[int]) -> int: """ Returns the maximum product that can be obtained by multiplying a contiguous subarray of the given integer list `numbers`. Example: >>> max_product_subarray([2, 3, -2, 4]) 6 >>> max_product_subarray((-2, 0, -1)) 0 >>> max_pro...
1,658
55
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\max_subarray_sum.py
python
Python
""" The maximum subarray sum problem is the task of finding the maximum sum that can be obtained from a contiguous subarray within a given array of numbers. For example, given the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the contiguous subarray with the maximum sum is [4, -1, 2, 1], so the maximum subarray sum is 6. Kad...
1,837
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\min_distance_up_bottom.py
python
Python
""" Author : Alexander Pantyukhin Date : October 14, 2022 This is an implementation of the up-bottom approach to find edit distance. The implementation was tested on Leetcode: https://leetcode.com/problems/edit-distance/ Levinstein distance Dynamic Programming: up -> down. """ import functools def min_distance_...
1,455
50
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\minimum_coin_change.py
python
Python
""" You have m types of coins available in infinite quantities where the value of each coins is given in the array S=[S0,... Sm-1] Can you determine number of ways of making change for n units using the given types of coins? https://www.hackerrank.com/challenges/coin-change/problem """ def dp_count(s, n): """ ...
1,138
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\minimum_cost_path.py
python
Python
# Youtube Explanation: https://www.youtube.com/watch?v=lBRtnuxg-gU from __future__ import annotations def minimum_cost_path(matrix: list[list[int]]) -> int: """ Find the minimum cost traced by all possible paths from top left to bottom right in a given matrix >>> minimum_cost_path([[2, 1], [3, 1], [...
973
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\minimum_partition.py
python
Python
""" Partition a set into two subsets such that the difference of subset sums is minimum """ def find_min(numbers: list[int]) -> int: """ >>> find_min([1, 2, 3, 4, 5]) 1 >>> find_min([5, 5, 5, 5, 5]) 5 >>> find_min([5, 5, 5, 5]) 0 >>> find_min([3]) 3 >>> find_min([]) 0 >...
1,738
77
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\minimum_size_subarray_sum.py
python
Python
import sys def minimum_subarray_sum(target: int, numbers: list[int]) -> int: """ Return the length of the shortest contiguous subarray in a list of numbers whose sum is at least target. Reference: https://stackoverflow.com/questions/8269916 >>> minimum_subarray_sum(7, [2, 3, 1, 2, 4, 3]) 2 >...
1,857
63
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\minimum_squares_to_represent_a_number.py
python
Python
import math import sys def minimum_squares_to_represent_a_number(number: int) -> int: """ Count the number of minimum squares to represent a number >>> minimum_squares_to_represent_a_number(25) 1 >>> minimum_squares_to_represent_a_number(37) 2 >>> minimum_squares_to_represent_a_number(21)...
1,475
50
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\minimum_steps_to_one.py
python
Python
""" YouTube Explanation: https://www.youtube.com/watch?v=f2xi3c1S95M Given an integer n, return the minimum steps from n to 1 AVAILABLE STEPS: * Decrement by 1 * if n is divisible by 2, divide by 2 * if n is divisible by 3, divide by 3 Example 1: n = 10 10 -> 9 -> 3 -> 1 Result: 3 steps Example 2: n = ...
1,416
67
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\minimum_tickets_cost.py
python
Python
""" Author : Alexander Pantyukhin Date : November 1, 2022 Task: Given a list of days when you need to travel. Each day is integer from 1 to 365. You are able to use tickets for 1 day, 7 days and 30 days. Each ticket has a cost. Find the minimum cost you need to travel every day in the given list of days. Impleme...
3,836
130
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\narcissistic_number.py
python
Python
""" Find all narcissistic numbers up to a given limit using dynamic programming. A narcissistic number (also known as an Armstrong number or plus perfect number) is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 153 is a narcissistic number because 153 = 1^3 ...
3,662
104
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\optimal_binary_search_tree.py
python
Python
#!/usr/bin/env python3 # This Python program implements an optimal binary search tree (abbreviated BST) # building dynamic programming algorithm that delivers O(n^2) performance. # # The goal of the optimal BST problem is to build a low-cost BST for a # given set of nodes, each with its own key and frequency. The freq...
5,562
145
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\palindrome_partitioning.py
python
Python
""" Given a string s, partition s such that every substring of the partition is a palindrome. Find the minimum cuts needed for a palindrome partitioning of s. Time Complexity: O(n^2) Space Complexity: O(n^2) For other explanations refer to: https://www.youtube.com/watch?v=_H8V5hJUGd0 """ def find_minimum_partitions(...
1,260
40
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\range_sum_query.py
python
Python
""" Author: Sanjay Muthu <https://github.com/XenoBytesX> This is an implementation of the Dynamic Programming solution to the Range Sum Query. The problem statement is: Given an array and q queries, each query stating you to find the sum of elements from l to r (inclusive) Example: arr = [1, 4, 6, 2, 61,...
2,754
93
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\regex_match.py
python
Python
""" Regex matching check if a text matches pattern or not. Pattern: 1. ``.`` Matches any single character. 2. ``*`` Matches zero or more of the preceding element. More info: https://medium.com/trick-the-interviwer/regular-expression-matching-9972eb74c03 """ def recursive_match(text: str, pattern: str) -...
2,646
100
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\rod_cutting.py
python
Python
""" This module provides two implementations for the rod-cutting problem: 1. A naive recursive implementation which has an exponential runtime 2. Two dynamic programming implementations which have quadratic runtime The rod-cutting problem is the problem of finding the maximum possible revenue obtainable from a rod...
6,270
219
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\smith_waterman.py
python
Python
""" https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm The Smith-Waterman algorithm is a dynamic programming algorithm used for sequence alignment. It is particularly useful for finding similarities between two sequences, such as DNA or protein sequences. In this implementation, gaps are penalized linearly,...
6,599
194
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\subset_generation.py
python
Python
def subset_combinations(elements: list[int], n: int) -> list: """ Compute n-element combinations from a given list using dynamic programming. Args: * `elements`: The list of elements from which combinations will be generated. * `n`: The number of elements in each combination. Returns: ...
2,206
64
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\sum_of_subset.py
python
Python
def is_sum_subset(arr: list[int], required_sum: int) -> bool: """ >>> is_sum_subset([2, 4, 6, 8], 5) False >>> is_sum_subset([2, 4, 6, 8], 14) True """ # a subset value says 1 if that subset sum can be formed else 0 # initially no subsets can be formed hence False/0 arr_len = len(arr...
1,101
36
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\trapped_water.py
python
Python
""" Given an array of non-negative integers representing an elevation map where the width of each bar is 1, this program calculates how much rainwater can be trapped. Example - height = (0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1) Output: 6 This problem can be solved using the concept of "DYNAMIC PROGRAMMING". We calculate t...
2,146
61
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\tribonacci.py
python
Python
# Tribonacci sequence using Dynamic Programming def tribonacci(num: int) -> list[int]: """ Given a number, return first n Tribonacci Numbers. >>> tribonacci(5) [0, 0, 1, 1, 2] >>> tribonacci(8) [0, 0, 1, 1, 2, 4, 7, 13] """ dp = [0] * num dp[2] = 1 for i in range(3, num): ...
476
25
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\viterbi.py
python
Python
from typing import Any def viterbi( observations_space: list, states_space: list, initial_probabilities: dict, transition_probabilities: dict, emission_probabilities: dict, ) -> list: """ Viterbi Algorithm, to find the most likely path of states from the start and the expected output. ...
13,850
378
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\wildcard_matching.py
python
Python
""" Author : ilyas dahhou Date : Oct 7, 2023 Task: Given an input string and a pattern, implement wildcard pattern matching with support for '?' and '*' where: '?' matches any single character. '*' matches any sequence of characters (including the empty sequence). The matching should cover the entire input string ...
1,828
69
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
dynamic_programming\word_break.py
python
Python
""" Author : Alexander Pantyukhin Date : December 12, 2022 Task: Given a string and a list of words, return true if the string can be segmented into a space-separated sequence of one or more words. Note that the same word may be reused multiple times in the segmentation. Implementation notes: Trie + Dynamic prog...
2,996
112
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\apparent_power.py
python
Python
import cmath import math def apparent_power( voltage: float, current: float, voltage_angle: float, current_angle: float ) -> complex: """ Calculate the apparent power in a single-phase AC circuit. Reference: https://en.wikipedia.org/wiki/AC_power#Apparent_power >>> apparent_power(100, 5, 0, 0) ...
1,083
38
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\builtin_voltage.py
python
Python
from math import log from scipy.constants import Boltzmann, physical_constants T = 300 # TEMPERATURE (unit = K) def builtin_voltage( donor_conc: float, # donor concentration acceptor_conc: float, # acceptor concentration intrinsic_conc: float, # intrinsic concentration ) -> float: """ This f...
2,495
68
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\capacitor_equivalence.py
python
Python
# https://farside.ph.utexas.edu/teaching/316/lectures/node46.html from __future__ import annotations def capacitor_parallel(capacitors: list[float]) -> float: """ Ceq = C1 + C2 + ... + Cn Calculate the equivalent resistance for any number of capacitors in parallel. >>> capacitor_parallel([5.71389, 12...
1,646
54
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\carrier_concentration.py
python
Python
# https://en.wikipedia.org/wiki/Charge_carrier_density # https://www.pveducation.org/pvcdrom/pn-junctions/equilibrium-carrier-concentration # http://www.ece.utep.edu/courses/ee3329/ee3329/Studyguide/ToC/Fundamentals/Carriers/concentrations.html from __future__ import annotations def carrier_concentration( electr...
2,830
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\charging_capacitor.py
python
Python
# source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RC_time_constant """ Description ----------- When a capacitor is connected with a potential source (AC or DC). It starts to charge at a general speed but when a resistor is connected in the circuit with in series to a capacitor then...
2,663
73
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\charging_inductor.py
python
Python
# source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RL_circuit """ Description ----------- Inductor is a passive electronic device which stores energy but unlike capacitor, it stores energy in its 'magnetic field' or 'magnetostatic field'. When inductor is connected to 'DC' current s...
3,614
98
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\circular_convolution.py
python
Python
# https://en.wikipedia.org/wiki/Circular_convolution """ Circular convolution, also known as cyclic convolution, is a special case of periodic convolution, which is the convolution of two periodic functions that have the same period. Periodic convolution arises, for example, in the context of the discrete-time Fourier...
3,554
99
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\coulombs_law.py
python
Python
# https://en.wikipedia.org/wiki/Coulomb%27s_law from __future__ import annotations COULOMBS_CONSTANT = 8.988e9 # units = N * m^s * C^-2 def couloumbs_law( force: float, charge1: float, charge2: float, distance: float ) -> dict[str, float]: """ Apply Coulomb's Law on any three given values. These can be...
2,791
86
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\electric_conductivity.py
python
Python
from __future__ import annotations ELECTRON_CHARGE = 1.6021e-19 # units = C def electric_conductivity( conductivity: float, electron_conc: float, mobility: float, ) -> tuple[str, float]: """ This function can calculate any one of the three - 1. Conductivity 2. Electron Concentration ...
2,646
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\electric_power.py
python
Python
# https://en.m.wikipedia.org/wiki/Electric_power from __future__ import annotations from typing import NamedTuple class Result(NamedTuple): name: str value: float def electric_power(voltage: float, current: float, power: float) -> tuple: """ This function can calculate any one of the three (voltage...
2,010
60
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\electrical_impedance.py
python
Python
"""Electrical impedance is the measure of the opposition that a circuit presents to a current when a voltage is applied. Impedance extends the concept of resistance to alternating current (AC) circuits. Source: https://en.wikipedia.org/wiki/Electrical_impedance """ from __future__ import annotations from math import ...
1,594
47
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\ic_555_timer.py
python
Python
from __future__ import annotations """ Calculate the frequency and/or duty cycle of an astable 555 timer. * https://en.wikipedia.org/wiki/555_timer_IC#Astable These functions take in the value of the external resistances (in ohms) and capacitance (in Microfarad), and calculates the following: ---...
2,708
76
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\ind_reactance.py
python
Python
# https://en.wikipedia.org/wiki/Electrical_reactance#Inductive_reactance from __future__ import annotations from math import pi def ind_reactance( inductance: float, frequency: float, reactance: float ) -> dict[str, float]: """ Calculate inductive reactance, frequency or inductance from two given electri...
2,060
70
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\ohms_law.py
python
Python
# https://en.wikipedia.org/wiki/Ohm%27s_law from __future__ import annotations def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/...
1,501
43
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\real_and_reactive_power.py
python
Python
import math def real_power(apparent_power: float, power_factor: float) -> float: """ Calculate real power from apparent power and power factor. Examples: >>> real_power(100, 0.9) 90.0 >>> real_power(0, 0.8) 0.0 >>> real_power(100, -0.9) -90.0 """ if ( not isinstanc...
1,255
50
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\resistor_color_code.py
python
Python
""" Title : Calculating the resistance of a n band resistor using the color codes Description : Resistors resist the flow of electrical current.Each one has a value that tells how strongly it resists current flow.This value's unit is the ohm, often noted with the Greek letter omega: Ω. The colored ban...
13,006
375
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\resistor_equivalence.py
python
Python
# https://byjus.com/equivalent-resistance-formula/ from __future__ import annotations def resistor_parallel(resistors: list[float]) -> float: """ Req = 1/ (1/R1 + 1/R2 + ... + 1/Rn) >>> resistor_parallel([3.21389, 2, 3]) 0.8737571620498019 >>> resistor_parallel([3.21389, 2, -3]) Traceback (m...
1,619
57
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\resonant_frequency.py
python
Python
# https://en.wikipedia.org/wiki/LC_circuit """An LC circuit, also called a resonant circuit, tank circuit, or tuned circuit, is an electric circuit consisting of an inductor, represented by the letter L, and a capacitor, represented by the letter C, connected together. The circuit can act as an electrical resonator, a...
1,647
51
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
electronics\wheatstone_bridge.py
python
Python
# https://en.wikipedia.org/wiki/Wheatstone_bridge from __future__ import annotations def wheatstone_solver( resistance_1: float, resistance_2: float, resistance_3: float ) -> float: """ This function can calculate the unknown resistance in an wheatstone network, given that the three other resistances ...
1,349
42
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
file_transfer\receive_file.py
python
Python
import socket def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 12312 sock.connect((host, port)) sock.send(b"Hello server!") with open("Received_file", "wb") as out_file: print("File opened") print("Receiving data...") ...
612
28
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
file_transfer\send_file.py
python
Python
def send_file(filename: str = "mytext.txt", testing: bool = False) -> None: import socket port = 12312 # Reserve a port for your service. sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name sock.bind((host, port)) # Bind to the port sock.list...
1,068
36
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
file_transfer\tests\test_send_file.py
test
Python
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket") @patch("builtins.open") def test_send_file_running_as_expected(file, sock): # ===== initialization ===== conn = Mock() sock.return_value.accept.return_value = conn, Mock() f = iter([1, None]) ...
1,044
32
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
financial\equated_monthly_installments.py
python
Python
""" Program to calculate the amortization amount per month, given - Principal borrowed - Rate of interest per annum - Years to repay the loan Wikipedia Reference: https://en.wikipedia.org/wiki/Equated_monthly_installment """ def equated_monthly_installments( principal: float, rate_per_annum: float, years_to_repa...
1,987
62
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
financial\exponential_moving_average.py
python
Python
""" Calculate the exponential moving average (EMA) on the series of stock prices. Wikipedia Reference: https://en.wikipedia.org/wiki/Exponential_smoothing https://www.investopedia.com/terms/e/ema.asp#toc-what-is-an-exponential -moving-average-ema Exponential moving average is used in finance to analyze changes stock p...
2,699
74
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
financial\interest.py
python
Python
# https://www.investopedia.com from __future__ import annotations def simple_interest( principal: float, daily_interest_rate: float, days_between_payments: float ) -> float: """ >>> simple_interest(18000.0, 0.06, 3) 3240.0 >>> simple_interest(0.5, 0.06, 3) 0.09 >>> simple_interest(18000.0...
3,789
121
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
financial\present_value.py
python
Python
""" Reference: https://www.investopedia.com/terms/p/presentvalue.asp An algorithm that calculates the present value of a stream of yearly cash flows given... 1. The discount rate (as a decimal, not a percent) 2. An array of cash flows, with the index of the cash flow being the associated year Note: This algorithm ass...
1,458
43
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
financial\price_plus_tax.py
python
Python
""" Calculate price plus tax of a good or service given its price and a tax rate. """ def price_plus_tax(price: float, tax_rate: float) -> float: """ >>> price_plus_tax(100, 0.25) 125.0 >>> price_plus_tax(125.50, 0.05) 131.775 """ return price * (1 + tax_rate) if __name__ == "__main__": ...
431
19
Python
TheAlgorithms/Python
TheAlgorithms
220,221
MIT
All Algorithms implemented in Python
financial\README.md
readme
Markdown
# Interest * Compound Interest: "Compound interest is calculated by multiplying the initial principal amount by one plus the annual interest rate raised to the number of compound periods minus one." [Compound Interest](https://www.investopedia.com/) * Simple Interest: "Simple interest paid or received over a certain p...
454
5