MCPcopy Create free account

hub / github.com/TheAlgorithms/Python / functions

Functions3,909 in github.com/TheAlgorithms/Python

Functiondecimal_to_hexadecimal
take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> de
conversions/decimal_to_hexadecimal.py:24
Functiondecimal_to_ipv4
Convert a decimal representation of an IP address to its IPv4 format. Args: decimal_ipv4: An integer representing the decimal IP add
conversions/ipv4_conversion.py:51
Functiondecimal_to_negative_base_2
This function returns the number negative base 2 of the decimal number of the input data. Args: int: The decimal number to c
maths/base_neg2_conversion.py:1
Functiondecipher
Deciphers a message given a cipher map :param message: Message to decipher :param cipher_map: Dictionary mapping to use :return: Dec
ciphers/simple_keyword_cypher.py:60
Functiondecode
Decodes from Baconian cipher >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB") 'hello world' >>> decode("AABBBAABAAA
ciphers/baconian_cipher.py:62
Methoddecode
Return the decoded version of message according to the polybius cipher >>> PolybiusCipher().decode("44154344 32154343112215") == "te
ciphers/polybius.py:74
Methoddecorator
Decorator version of LRU Cache Decorated function must be function of T -> U
other/lru_cache.py:298
Methoddecorator
Decorator version of LFU Cache Decorated function must be function of T -> U
other/lfu_cache.py:281
Methoddecrypt
input: 'content' of type list and 'key' of type int output: decrypted string 'content' as a list of chars if key not passed t
ciphers/xor_cipher.py:68
Functiondecrypt_caesar_with_chi_squared
Basic Usage =========== Arguments: * `ciphertext` (str): the text to decode (encoded with the caesar cipher) Optional Argumen
ciphers/decrypt_caesar_with_chi_squared.py:5
Methoddecrypt_file
input: filename (str) and a key (int) output: returns true if decrypt process was successful otherwise false if key n
ciphers/xor_cipher.py:212
Methoddegree
(self, u)
graphs/directed_and_undirected_weighted_graph.py:368
Methoddelete
(self, data)
data_structures/linked_list/doubly_linked_list.py:159
Methoddelete_min
delete min element and return it
data_structures/heap/binomial_heap.py:256
Methoddelete_value
(self, value)
data_structures/linked_list/doubly_linked_list_two.py:141
Methoddepth
Returns the depth of the tree >>> BinaryTree(Node(1)).depth() 1 >>> BinaryTree.small_tree().depth() 2
data_structures/binary_tree/basic_binary_tree.py:75
Functiondepth_first_search
Recursive Backtracking Depth First Search Algorithm Starting from top left of a matrix, count the number of paths that can reach the bot
matrix/count_paths.py:23
Methoddequeue
Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (
data_structures/queues/circular_queue_linked_list.py:111
Methoddequeue
This function removes an element from the queue using on self.front value as an index and returns it >>> cq = CircularQueue(
data_structures/queues/circular_queue.py:81
Methodderivative
Returns the derivative of the polynomial. >>> p = Polynomial(2, [1, 2, 3]) >>> p.derivative() 6x + 2
maths/polynomials/single_indeterminate_operations.py:135
Functiondeserialize
Deserialize a string to a binary tree. Args: data(str): The serialized string. Returns: The root of the binary tree.
data_structures/binary_tree/serialize_deserialize_binary_tree.py:86
Functiondfs
>>> dfs({1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}, 1) 1 2 4 5 3
graphs/basic_graphs.py:79
Methoddfs_time
(self, s=-2, e=-1)
graphs/directed_and_undirected_weighted_graph.py:251
Methoddfs_time
(self, s=-2, e=-1)
graphs/directed_and_undirected_weighted_graph.py:479
Methoddiameter
>>> Circle(5).diameter 10
geometry/geometry.py:135
Functiondifferent_signs
Return True if numbers have opposite signs False otherwise. >>> different_signs(1, -1) True >>> different_signs(1, 1) False
bit_manipulation/numbers_different_signs.py:14
Functiondijk
dijk({1: [(2, 7), (3, 9), (6, 14)], 2: [(1, 7), (3, 10), (4, 15)], 3: [(1, 9), (2, 10), (4, 11), (6, 2)], 4: [(2, 15), (3
graphs/basic_graphs.py:149
Functiondijkstra
Implements Dijkstra's algorithm on a binary grid. Args: grid (np.ndarray): A 2D numpy array representing the grid. 1 represe
graphs/dijkstra_binary_grid.py:14
Functiondiophantine_all_soln
Lemma : if n|ab and gcd(a,n) = 1, then n|b. Finding All solutions of Diophantine Equations: Theorem : Let gcd(a,b) = d, a = d*p, b = d*
blockchain/diophantine_equation.py:33
Methoddisp
(self, ind: int = 1)
machine_learning/frequent_pattern_growth.py:49
Functiondistance
>>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}")
maths/pythagoras.py:16
Methoddistinct_weight
For Boruvks's algorithm the weights should be distinct Converts the weights to be distinct
graphs/minimum_spanning_tree_boruvka.py:35
Functiondistribute_coins
>>> distribute_coins(TreeNode(3, TreeNode(0), TreeNode(0))) 2 >>> distribute_coins(TreeNode(0, TreeNode(3), TreeNode(0))) 3 >>> d
data_structures/binary_tree/distribute_coins.py:58
Functiondjb2
Implementation of djb2 hash algorithm that is popular because of it's magic constants. >>> djb2('Algorithms') 3782405311 >>> dj
hashes/djb2.py:21
Functiondna
https://en.wikipedia.org/wiki/DNA Returns the second side of a DNA strand >>> dna("GCTA") 'CGAT' >>> dna("ATGC") 'TACG'
strings/dna.py:4
Methoddo_round
(self, x)
neural_network/convolution_neural_network.py:106
Functiondocument_frequency
Calculate the number of documents in a corpus that contain a given term @params : term, the term to search each document for, and corpus,
machine_learning/word_frequency_functions.py:64
Functiondodecahedron_surface_area
Calculates the surface area of a regular dodecahedron a = 3 * ((25 + 10 * (5** (1 / 2))) ** (1 / 2 )) * (e**2) where: a --> is the ar
maths/dodecahedron.py:9
Functiondodecahedron_volume
Calculates the volume of a regular dodecahedron v = ((15 + (7 * (5** (1 / 2)))) / 4) * (e**3) where: v --> is the volume of the dodec
maths/dodecahedron.py:40
Functiondoppler_effect
Input Parameters: ----------------- org_freq: frequency of the wave when the source is stationary wave_vel: velocity of the wave in t
physics/doppler_frequency.py:47
Functiondouble_factorial_iterative
Compute double factorial using iterative method. To learn about the theory behind this algorithm: https://en.wikipedia.org/wiki/Double_f
maths/double_factorial.py:28
Functiondouble_factorial_recursive
Compute double factorial using recursive method. Recursion can be costly for large numbers. To learn about the theory behind this algori
maths/double_factorial.py:1
Functiondp_count
>>> dp_count([1, 2, 3], 4) 4 >>> dp_count([1, 2, 3], 7) 8 >>> dp_count([2, 5, 3, 6], 10) 5 >>> dp_count([10], 99) 0
dynamic_programming/minimum_coin_change.py:10
Functiondp_match
r""" Dynamic programming matching algorithm. | Time complexity: O(\|text\| * \|pattern\|) | Space complexity: O(\|text\| * \|pattern\|)
dynamic_programming/regex_match.py:52
Methoddraw_error
()
neural_network/convolution_neural_network.py:298
Methoddvi
Simple Ratio self.nir/self.red Difference Vegetation Index, Vegetation Index Number (VIN) https://www.indexdatabase.de/db/i-s
digital_image_processing/index_calculation.py:511
Functionedglist
r""" Get the edges and number of edges from the user Parameters: None Returns: tuple: A tuple containing a list of edges
graphs/basic_graphs.py:313
Functioneffusion_ratio
Input Parameters: ----------------- molar_mass_1: Molar mass of the first gas (g/mol, kg/kmol, etc.) molar_mass_2: Molar mass of the
physics/grahams_law.py:42
Functionelectric_conductivity
This function can calculate any one of the three - 1. Conductivity 2. Electron Concentration 3. Electron Mobility This is calcula
electronics/electric_conductivity.py:6
Functionelectric_power
This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below:
electronics/electric_power.py:12
Functionelectrical_impedance
Apply Electrical Impedance formula, on any two given electrical values, which can be resistance, reactance, and impedance, and then in a Pyth
electronics/electrical_impedance.py:12
Functionelf_hash
Implementation of ElfHash Algorithm, a variant of PJW hash function. >>> elf_hash('lorem ipsum') 253956621
hashes/elf.py:1
Methodemail
(self)
web_programming/instagram_crawler.py:78
Functionemitter_converter
:param size_par: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliab
hashes/hamming_code.py:71
Functionencipher
Enciphers a message given a cipher map. :param message: Message to encipher :param cipher_map: Cipher map :return: enciphered string
ciphers/simple_keyword_cypher.py:46
Functionencode
Encodes to Baconian cipher >>> encode("hello") 'AABBBAABAAABABAABABAABBAB' >>> encode("hello world") 'AABBBAABAAABABAABABAABBAB
ciphers/baconian_cipher.py:40
Methodencode
Return the encoded version of message according to the polybius cipher >>> PolybiusCipher().encode("test message") == "44154344 3215
ciphers/polybius.py:51
Functionencrypt
Shuffles the character of a string by placing each of them in a grid (the height is dependent on the key) in a zigzag formation and re
ciphers/rail_fence_cipher.py:4
Methodencrypt
input: 'content' of type string and 'key' of type int output: encrypted string 'content' as a list of chars if key not passed
ciphers/xor_cipher.py:33
Methodencrypt_file
input: filename (str) and a key (int) output: returns true if encrypt process was successful otherwise false if key n
ciphers/xor_cipher.py:185
Functionenergy_conversion
Conversion of energy units. >>> energy_conversion("joule", "joule", 1) 1.0 >>> energy_conversion("joule", "kilojoule", 1) 0.001
conversions/energy_conversions.py:45
Functionenergy_from_mass
Calculates the Energy equivalence of the Mass using E = mc² in SI units J from Mass in kg. mass (float): Mass of body. Usage exampl
physics/mass_energy_equivalence.py:24
Functionenglish_freq_match_score
>>> english_freq_match_score('Hello World') 1
strings/frequency_finder.py:82
Methodenqueue
Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b')
data_structures/queues/circular_queue_linked_list.py:86
Methodenqueue
This function inserts an element at the end of the queue using self.rear value as an index. >>> cq = CircularQueue(5)
data_structures/queues/circular_queue.py:50
Methodepochs_completed
(self)
neural_network/input_data.py:197
Functionequated_monthly_installments
Formula for amortization amount per month: A = p * r * (1 + r)^n / ((1 + r)^n - 1) where p is the principal, r is the rate of interest pe
financial/equated_monthly_installments.py:11
Functionequilibrium_index
Find the equilibrium index of an array. Args: arr (list[int]): The input array of integers. Returns: int: The equilibri
data_structures/arrays/equilibrium_index_in_array.py:23
Methodestimated_error_rate
(self)
data_structures/hashing/bloom_filter.py:104
Functioneuclidean_distance
Calculate the distance between the two endpoints of two vectors. A vector is defined as a list, tuple, or numpy 1D array. >>> float(eucli
maths/euclidean_distance.py:12
Functioneuclidean_distance_no_np
Calculate the distance between the two endpoints of two vectors without numpy. A vector is defined as a list, tuple, or numpy 1D array. >
maths/euclidean_distance.py:28
Functioneuler_modified
Calculate solution at each step to an ODE using Euler's Modified Method The Euler Method is straightforward to implement, but can't give accu
maths/euler_modified.py:6
Functioneuler_phi
Calculate Euler's Phi Function. >>> euler_phi(100) 40 >>> euler_phi(0) Traceback (most recent call last): ... ValueE
maths/basic_maths.py:98
Functioneval_exponential
Evaluate $e^z + c$. >>> float(eval_exponential(0, 0)) 1.0 >>> bool(abs(eval_exponential(1, np.pi*1.j)) < 1e-15) True >>> bool
fractals/julia_sets.py:40
Functioneval_quadratic_polynomial
>>> eval_quadratic_polynomial(0, 2) 4 >>> eval_quadratic_polynomial(-1, 1) 0 >>> round(eval_quadratic_polynomial(1.j, 0).imag)
fractals/julia_sets.py:53
Methodevaluate
Evaluates the polynomial at x. >>> p = Polynomial(2, [1, 2, 3]) >>> p.evaluate(2) 17
maths/polynomials/single_indeterminate_operations.py:90
Functionevaluate_recursive
Alternative recursive implementation >>> evaluate_recursive(['2']) 2 >>> expression = ['+', '*', '2', '3', '/', '8', '4'] >>> ev
data_structures/stacks/prefix_evaluation.py:58
Methodevi
Enhanced Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=16 :return: index
digital_image_processing/index_calculation.py:349
Functionexample
Example function to calculate Mel Frequency Cepstral Coefficients (MFCCs) from an audio file. Args: wav_file_path: The path to t
machine_learning/mfcc.py:456
Functionexcel_title_to_column
Given a string column_title that represents the column title in an Excel sheet, return its corresponding column number. >>> excel_ti
conversions/excel_title_to_column.py:1
Functionexcess_3_code
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.wikiped
bit_manipulation/excess_3_code.py:1
Functionexplicit_euler
Calculate numeric solution at each step to an ODE using Euler's Method For reference to Euler's method refer to https://en.wikipedia.org/wiki/Eul
maths/euler_method.py:6
Functionexponential_linear_unit
Implements the ELU activation function. Parameters: vector: the array containing input of elu activation
neural_network/activation_functions/exponential_linear_unit.py:14
Functionexponential_search
Pure implementation of an exponential search algorithm in Python Resources used: https://en.wikipedia.org/wiki/Exponential_search Be care
searches/binary_search.py:360
Methodextendleft
Appends every value of iterable to the beginning of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3])
data_structures/queues/double_ended_queue.py:212
Methodextract_top
Return top item tuple (Calculated value, item) from heap and removes it as well if present
data_structures/heap/heap_generic.py:120
Functionf
(x)
maths/line_length.py:57
Functionf
(x)
maths/area_under_curve.py:53
Functionf
(y)
maths/dual_number_automatic_differentiation.py:136
Functionf
function is f(x) = x^3 - 2x - 5 >>> f(2) -1.0
maths/numerical_analysis/intersection.py:44
Functionf
(x)
maths/numerical_analysis/numerical_integration.py:57
Functionf
(x: float)
maths/numerical_analysis/integration_by_simpson_approx.py:21
Functionfactorial
>>> factorial(7) 5040 >>> factorial(-1) Traceback (most recent call last): ... ValueError: Number should not be negative.
dynamic_programming/factorial.py:7
Functionfactorial_recursive
Calculate the factorial of a positive integer https://en.wikipedia.org/wiki/Factorial >>> import math >>> all(factorial_recursive(i)
maths/factorial.py:38
Functionfactors_of_a_number
>>> factors_of_a_number(1) [1] >>> factors_of_a_number(5) [1, 5] >>> factors_of_a_number(24) [1, 2, 3, 4, 6, 8, 12, 24] >
maths/factors.py:5
Functionfahrenheit_to_celsius
Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenh
conversions/temperature_conversions.py:80
Functionfahrenheit_to_kelvin
Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenhe
conversions/temperature_conversions.py:110
Functionfahrenheit_to_rankine
Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenh
conversions/temperature_conversions.py:140
Functionfast_primes
Return a list of all primes numbers up to max. >>> list(fast_primes(0)) [] >>> list(fast_primes(-1)) [] >>> list(fast_primes(
maths/prime_numbers.py:61
Functionfib
input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 >>> fib(0) 1 >>> fib(5) 8 >>> fib(20) 10
maths/primelib.py:800
← previousnext →3,001–3,100 of 3,909, ranked by callers