Skip to content

Commit db81f44

Browse files
Merge branch 'TheAlgorithms:master' into master
2 parents 5fc64e6 + 777eca8 commit db81f44

File tree

93 files changed

+3443
-640
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

93 files changed

+3443
-640
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
repos:
22
- repo: https://github.com/pre-commit/pre-commit-hooks
3-
rev: v4.4.0
3+
rev: v4.5.0
44
hooks:
55
- id: check-executables-have-shebangs
66
- id: check-toml
@@ -51,7 +51,7 @@ repos:
5151
- id: validate-pyproject
5252

5353
- repo: https://github.com/pre-commit/mirrors-mypy
54-
rev: v1.5.1
54+
rev: v1.6.0
5555
hooks:
5656
- id: mypy
5757
args:

DIRECTORY.md

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,12 @@
5454
* [Largest Pow Of Two Le Num](bit_manipulation/largest_pow_of_two_le_num.py)
5555
* [Missing Number](bit_manipulation/missing_number.py)
5656
* [Numbers Different Signs](bit_manipulation/numbers_different_signs.py)
57+
* [Power Of 4](bit_manipulation/power_of_4.py)
5758
* [Reverse Bits](bit_manipulation/reverse_bits.py)
5859
* [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py)
5960

6061
## Blockchain
61-
* [Chinese Remainder Theorem](blockchain/chinese_remainder_theorem.py)
6262
* [Diophantine Equation](blockchain/diophantine_equation.py)
63-
* [Modular Division](blockchain/modular_division.py)
6463

6564
## Boolean Algebra
6665
* [And Gate](boolean_algebra/and_gate.py)
@@ -101,11 +100,13 @@
101100
* [Diffie Hellman](ciphers/diffie_hellman.py)
102101
* [Elgamal Key Generator](ciphers/elgamal_key_generator.py)
103102
* [Enigma Machine2](ciphers/enigma_machine2.py)
103+
* [Fractionated Morse Cipher](ciphers/fractionated_morse_cipher.py)
104104
* [Hill Cipher](ciphers/hill_cipher.py)
105105
* [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py)
106106
* [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py)
107107
* [Morse Code](ciphers/morse_code.py)
108108
* [Onepad Cipher](ciphers/onepad_cipher.py)
109+
* [Permutation Cipher](ciphers/permutation_cipher.py)
109110
* [Playfair Cipher](ciphers/playfair_cipher.py)
110111
* [Polybius](ciphers/polybius.py)
111112
* [Porta Cipher](ciphers/porta_cipher.py)
@@ -172,6 +173,7 @@
172173

173174
## Data Structures
174175
* Arrays
176+
* [Equilibrium Index In Array](data_structures/arrays/equilibrium_index_in_array.py)
175177
* [Median Two Array](data_structures/arrays/median_two_array.py)
176178
* [Permutations](data_structures/arrays/permutations.py)
177179
* [Prefix Sum](data_structures/arrays/prefix_sum.py)
@@ -352,6 +354,7 @@
352354
* [Smith Waterman](dynamic_programming/smith_waterman.py)
353355
* [Subset Generation](dynamic_programming/subset_generation.py)
354356
* [Sum Of Subset](dynamic_programming/sum_of_subset.py)
357+
* [Trapped Water](dynamic_programming/trapped_water.py)
355358
* [Tribonacci](dynamic_programming/tribonacci.py)
356359
* [Viterbi](dynamic_programming/viterbi.py)
357360
* [Word Break](dynamic_programming/word_break.py)
@@ -360,6 +363,7 @@
360363
* [Apparent Power](electronics/apparent_power.py)
361364
* [Builtin Voltage](electronics/builtin_voltage.py)
362365
* [Carrier Concentration](electronics/carrier_concentration.py)
366+
* [Charging Capacitor](electronics/charging_capacitor.py)
363367
* [Circular Convolution](electronics/circular_convolution.py)
364368
* [Coulombs Law](electronics/coulombs_law.py)
365369
* [Electric Conductivity](electronics/electric_conductivity.py)
@@ -466,6 +470,8 @@
466470
* [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py)
467471

468472
## Greedy Methods
473+
* [Best Time To Buy And Sell Stock](greedy_methods/best_time_to_buy_and_sell_stock.py)
474+
* [Fractional Cover Problem](greedy_methods/fractional_cover_problem.py)
469475
* [Fractional Knapsack](greedy_methods/fractional_knapsack.py)
470476
* [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py)
471477
* [Gas Station](greedy_methods/gas_station.py)
@@ -524,6 +530,11 @@
524530
* Local Weighted Learning
525531
* [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py)
526532
* [Logistic Regression](machine_learning/logistic_regression.py)
533+
* Loss Functions
534+
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
535+
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
536+
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
537+
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
527538
* [Mfcc](machine_learning/mfcc.py)
528539
* [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py)
529540
* [Polynomial Regression](machine_learning/polynomial_regression.py)
@@ -556,15 +567,17 @@
556567
* [Bell Numbers](maths/bell_numbers.py)
557568
* [Binary Exp Mod](maths/binary_exp_mod.py)
558569
* [Binary Exponentiation](maths/binary_exponentiation.py)
559-
* [Binary Exponentiation 3](maths/binary_exponentiation_3.py)
570+
* [Binary Exponentiation 2](maths/binary_exponentiation_2.py)
560571
* [Binary Multiplication](maths/binary_multiplication.py)
561572
* [Binomial Coefficient](maths/binomial_coefficient.py)
562573
* [Binomial Distribution](maths/binomial_distribution.py)
563574
* [Bisection](maths/bisection.py)
564575
* [Carmichael Number](maths/carmichael_number.py)
565576
* [Catalan Number](maths/catalan_number.py)
566577
* [Ceil](maths/ceil.py)
578+
* [Chebyshev Distance](maths/chebyshev_distance.py)
567579
* [Check Polygon](maths/check_polygon.py)
580+
* [Chinese Remainder Theorem](maths/chinese_remainder_theorem.py)
568581
* [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py)
569582
* [Collatz Sequence](maths/collatz_sequence.py)
570583
* [Combinations](maths/combinations.py)
@@ -588,10 +601,10 @@
588601
* [Find Min](maths/find_min.py)
589602
* [Floor](maths/floor.py)
590603
* [Gamma](maths/gamma.py)
591-
* [Gamma Recursive](maths/gamma_recursive.py)
592604
* [Gaussian](maths/gaussian.py)
593605
* [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py)
594606
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
607+
* [Germain Primes](maths/germain_primes.py)
595608
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
596609
* [Greedy Coin Change](maths/greedy_coin_change.py)
597610
* [Hamming Numbers](maths/hamming_numbers.py)
@@ -619,7 +632,9 @@
619632
* [Matrix Exponentiation](maths/matrix_exponentiation.py)
620633
* [Max Sum Sliding Window](maths/max_sum_sliding_window.py)
621634
* [Median Of Two Arrays](maths/median_of_two_arrays.py)
635+
* [Minkowski Distance](maths/minkowski_distance.py)
622636
* [Mobius Function](maths/mobius_function.py)
637+
* [Modular Division](maths/modular_division.py)
623638
* [Modular Exponential](maths/modular_exponential.py)
624639
* [Monte Carlo](maths/monte_carlo.py)
625640
* [Monte Carlo Dice](maths/monte_carlo_dice.py)
@@ -721,11 +736,16 @@
721736
## Neural Network
722737
* [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py)
723738
* Activation Functions
739+
* [Binary Step](neural_network/activation_functions/binary_step.py)
724740
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
725741
* [Leaky Rectified Linear Unit](neural_network/activation_functions/leaky_rectified_linear_unit.py)
742+
* [Mish](neural_network/activation_functions/mish.py)
726743
* [Rectified Linear Unit](neural_network/activation_functions/rectified_linear_unit.py)
727744
* [Scaled Exponential Linear Unit](neural_network/activation_functions/scaled_exponential_linear_unit.py)
728745
* [Sigmoid Linear Unit](neural_network/activation_functions/sigmoid_linear_unit.py)
746+
* [Soboleva Modified Hyperbolic Tangent](neural_network/activation_functions/soboleva_modified_hyperbolic_tangent.py)
747+
* [Softplus](neural_network/activation_functions/softplus.py)
748+
* [Squareplus](neural_network/activation_functions/squareplus.py)
729749
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
730750
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
731751
* [Perceptron](neural_network/perceptron.py)
@@ -748,6 +768,7 @@
748768
* [Linear Congruential Generator](other/linear_congruential_generator.py)
749769
* [Lru Cache](other/lru_cache.py)
750770
* [Magicdiamondpattern](other/magicdiamondpattern.py)
771+
* [Majority Vote Algorithm](other/majority_vote_algorithm.py)
751772
* [Maximum Subsequence](other/maximum_subsequence.py)
752773
* [Nested Brackets](other/nested_brackets.py)
753774
* [Number Container System](other/number_container_system.py)
@@ -778,6 +799,7 @@
778799
* [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)
779800
* [Photoelectric Effect](physics/photoelectric_effect.py)
780801
* [Potential Energy](physics/potential_energy.py)
802+
* [Reynolds Number](physics/reynolds_number.py)
781803
* [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py)
782804
* [Shear Stress](physics/shear_stress.py)
783805
* [Speed Of Sound](physics/speed_of_sound.py)
@@ -1100,6 +1122,7 @@
11001122
* [Interpolation Search](searches/interpolation_search.py)
11011123
* [Jump Search](searches/jump_search.py)
11021124
* [Linear Search](searches/linear_search.py)
1125+
* [Median Of Medians](searches/median_of_medians.py)
11031126
* [Quick Select](searches/quick_select.py)
11041127
* [Sentinel Linear Search](searches/sentinel_linear_search.py)
11051128
* [Simple Binary Search](searches/simple_binary_search.py)
@@ -1196,11 +1219,11 @@
11961219
* [Rabin Karp](strings/rabin_karp.py)
11971220
* [Remove Duplicate](strings/remove_duplicate.py)
11981221
* [Reverse Letters](strings/reverse_letters.py)
1199-
* [Reverse Long Words](strings/reverse_long_words.py)
12001222
* [Reverse Words](strings/reverse_words.py)
12011223
* [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py)
12021224
* [Split](strings/split.py)
12031225
* [String Switch Case](strings/string_switch_case.py)
1226+
* [Strip](strings/strip.py)
12041227
* [Text Justification](strings/text_justification.py)
12051228
* [Top K Frequent Words](strings/top_k_frequent_words.py)
12061229
* [Upper](strings/upper.py)

arithmetic_analysis/gaussian_elimination.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def retroactive_resolution(
3434
x: NDArray[float64] = np.zeros((rows, 1), dtype=float)
3535
for row in reversed(range(rows)):
3636
total = np.dot(coefficients[row, row + 1 :], x[row + 1 :])
37-
x[row, 0] = (vector[row] - total) / coefficients[row, row]
37+
x[row, 0] = (vector[row][0] - total[0]) / coefficients[row, row]
3838

3939
return x
4040

backtracking/power_sum.py

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
The only solution is 2^2+3^2. Constraints: 1<=X<=1000, 2<=N<=10.
77
"""
88

9-
from math import pow
10-
119

1210
def backtrack(
1311
needed_sum: int,
@@ -19,25 +17,25 @@ def backtrack(
1917
"""
2018
>>> backtrack(13, 2, 1, 0, 0)
2119
(0, 1)
22-
>>> backtrack(100, 2, 1, 0, 0)
23-
(0, 3)
24-
>>> backtrack(100, 3, 1, 0, 0)
20+
>>> backtrack(10, 2, 1, 0, 0)
21+
(0, 1)
22+
>>> backtrack(10, 3, 1, 0, 0)
23+
(0, 0)
24+
>>> backtrack(20, 2, 1, 0, 0)
2525
(0, 1)
26-
>>> backtrack(800, 2, 1, 0, 0)
27-
(0, 561)
28-
>>> backtrack(1000, 10, 1, 0, 0)
26+
>>> backtrack(15, 10, 1, 0, 0)
2927
(0, 0)
30-
>>> backtrack(400, 2, 1, 0, 0)
31-
(0, 55)
32-
>>> backtrack(50, 1, 1, 0, 0)
33-
(0, 3658)
28+
>>> backtrack(16, 2, 1, 0, 0)
29+
(0, 1)
30+
>>> backtrack(20, 1, 1, 0, 0)
31+
(0, 64)
3432
"""
3533
if current_sum == needed_sum:
3634
# If the sum of the powers is equal to needed_sum, then we have a solution.
3735
solutions_count += 1
3836
return current_sum, solutions_count
3937

40-
i_to_n = int(pow(current_number, power))
38+
i_to_n = current_number**power
4139
if current_sum + i_to_n <= needed_sum:
4240
# If the sum of the powers is less than needed_sum, then continue adding powers.
4341
current_sum += i_to_n
@@ -57,17 +55,17 @@ def solve(needed_sum: int, power: int) -> int:
5755
"""
5856
>>> solve(13, 2)
5957
1
60-
>>> solve(100, 2)
61-
3
62-
>>> solve(100, 3)
58+
>>> solve(10, 2)
6359
1
64-
>>> solve(800, 2)
65-
561
66-
>>> solve(1000, 10)
60+
>>> solve(10, 3)
6761
0
68-
>>> solve(400, 2)
69-
55
70-
>>> solve(50, 1)
62+
>>> solve(20, 2)
63+
1
64+
>>> solve(15, 10)
65+
0
66+
>>> solve(16, 2)
67+
1
68+
>>> solve(20, 1)
7169
Traceback (most recent call last):
7270
...
7371
ValueError: Invalid input

backtracking/word_search.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,7 @@ def word_exists(board: list[list[str]], word: str) -> bool:
9898
False
9999
>>> word_exists([["A"]], "A")
100100
True
101-
>>> word_exists([["A","A","A","A","A","A"],
102-
... ["A","A","A","A","A","A"],
103-
... ["A","A","A","A","A","A"],
104-
... ["A","A","A","A","A","A"],
105-
... ["A","A","A","A","A","B"],
106-
... ["A","A","A","A","B","A"]],
107-
... "AAAAAAAAAAAAABB")
101+
>>> word_exists([["B", "A", "A"], ["A", "A", "A"], ["A", "B", "A"]], "ABB")
108102
False
109103
>>> word_exists([["A"]], 123)
110104
Traceback (most recent call last):

bit_manipulation/missing_number.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,18 @@ def find_missing_number(nums: list[int]) -> int:
1111
Example:
1212
>>> find_missing_number([0, 1, 3, 4])
1313
2
14+
>>> find_missing_number([1, 3, 4, 5, 6])
15+
2
16+
>>> find_missing_number([6, 5, 4, 2, 1])
17+
3
18+
>>> find_missing_number([6, 1, 5, 3, 4])
19+
2
1420
"""
15-
n = len(nums)
16-
missing_number = n
21+
low = min(nums)
22+
high = max(nums)
23+
missing_number = high
1724

18-
for i in range(n):
19-
missing_number ^= i ^ nums[i]
25+
for i in range(low, high):
26+
missing_number ^= i ^ nums[i - low]
2027

2128
return missing_number

bit_manipulation/power_of_4.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
3+
Task:
4+
Given a positive int number. Return True if this number is power of 4
5+
or False otherwise.
6+
7+
Implementation notes: Use bit manipulation.
8+
For example if the number is the power of 2 it's bits representation:
9+
n = 0..100..00
10+
n - 1 = 0..011..11
11+
12+
n & (n - 1) - no intersections = 0
13+
If the number is a power of 4 then it should be a power of 2
14+
and the set bit should be at an odd position.
15+
"""
16+
17+
18+
def power_of_4(number: int) -> bool:
19+
"""
20+
Return True if this number is power of 4 or False otherwise.
21+
22+
>>> power_of_4(0)
23+
Traceback (most recent call last):
24+
...
25+
ValueError: number must be positive
26+
>>> power_of_4(1)
27+
True
28+
>>> power_of_4(2)
29+
False
30+
>>> power_of_4(4)
31+
True
32+
>>> power_of_4(6)
33+
False
34+
>>> power_of_4(8)
35+
False
36+
>>> power_of_4(17)
37+
False
38+
>>> power_of_4(64)
39+
True
40+
>>> power_of_4(-1)
41+
Traceback (most recent call last):
42+
...
43+
ValueError: number must be positive
44+
>>> power_of_4(1.2)
45+
Traceback (most recent call last):
46+
...
47+
TypeError: number must be an integer
48+
49+
"""
50+
if not isinstance(number, int):
51+
raise TypeError("number must be an integer")
52+
if number <= 0:
53+
raise ValueError("number must be positive")
54+
if number & (number - 1) == 0:
55+
c = 0
56+
while number:
57+
c += 1
58+
number >>= 1
59+
return c % 2 == 1
60+
else:
61+
return False
62+
63+
64+
if __name__ == "__main__":
65+
import doctest
66+
67+
doctest.testmod()

0 commit comments

Comments
 (0)