Skip to content

Commit 474771e

Browse files
authored
Merge branch 'TheAlgorithms:master' into add_perfect_cube_binary_search
2 parents 8b417b3 + b5786c8 commit 474771e

Some content is hidden

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

53 files changed

+2304
-427
lines changed

.github/ISSUE_TEMPLATE/feature_request.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@ body:
66
attributes:
77
value: >
88
Before requesting please search [existing issues](https://github.com/TheAlgorithms/Python/labels/enhancement).
9+
Do not create issues to implement new algorithms as these will be closed.
910
Usage questions such as "How do I...?" belong on the
1011
[Discord](https://discord.gg/c7MnfGFGa6) and will be closed.
1112
1213
- type: textarea
1314
attributes:
1415
label: "Feature description"
1516
description: >
16-
This could be new algorithms, data structures or improving any existing
17-
implementations.
17+
This could include new topics or improving any existing implementations.
1818
validations:
1919
required: true

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ repos:
4646
pass_filenames: false
4747

4848
- repo: https://github.com/abravalheri/validate-pyproject
49-
rev: v0.14
49+
rev: v0.15
5050
hooks:
5151
- id: validate-pyproject
5252

DIRECTORY.md

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,9 @@
6363

6464
## Boolean Algebra
6565
* [And Gate](boolean_algebra/and_gate.py)
66+
* [Imply Gate](boolean_algebra/imply_gate.py)
6667
* [Nand Gate](boolean_algebra/nand_gate.py)
68+
* [Nimply Gate](boolean_algebra/nimply_gate.py)
6769
* [Nor Gate](boolean_algebra/nor_gate.py)
6870
* [Not Gate](boolean_algebra/not_gate.py)
6971
* [Or Gate](boolean_algebra/or_gate.py)
@@ -119,9 +121,9 @@
119121
* [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py)
120122
* [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py)
121123
* [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py)
122-
* [Trafid Cipher](ciphers/trafid_cipher.py)
123124
* [Transposition Cipher](ciphers/transposition_cipher.py)
124125
* [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py)
126+
* [Trifid Cipher](ciphers/trifid_cipher.py)
125127
* [Vigenere Cipher](ciphers/vigenere_cipher.py)
126128
* [Xor Cipher](ciphers/xor_cipher.py)
127129

@@ -174,10 +176,13 @@
174176
## Data Structures
175177
* Arrays
176178
* [Equilibrium Index In Array](data_structures/arrays/equilibrium_index_in_array.py)
179+
* [Find Triplets With 0 Sum](data_structures/arrays/find_triplets_with_0_sum.py)
177180
* [Median Two Array](data_structures/arrays/median_two_array.py)
181+
* [Pairs With Given Sum](data_structures/arrays/pairs_with_given_sum.py)
178182
* [Permutations](data_structures/arrays/permutations.py)
179183
* [Prefix Sum](data_structures/arrays/prefix_sum.py)
180184
* [Product Sum](data_structures/arrays/product_sum.py)
185+
* [Sparse Table](data_structures/arrays/sparse_table.py)
181186
* Binary Tree
182187
* [Avl Tree](data_structures/binary_tree/avl_tree.py)
183188
* [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py)
@@ -187,10 +192,12 @@
187192
* [Binary Tree Node Sum](data_structures/binary_tree/binary_tree_node_sum.py)
188193
* [Binary Tree Path Sum](data_structures/binary_tree/binary_tree_path_sum.py)
189194
* [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py)
195+
* [Diameter Of Binary Tree](data_structures/binary_tree/diameter_of_binary_tree.py)
190196
* [Diff Views Of Binary Tree](data_structures/binary_tree/diff_views_of_binary_tree.py)
191197
* [Distribute Coins](data_structures/binary_tree/distribute_coins.py)
192198
* [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py)
193199
* [Flatten Binarytree To Linkedlist](data_structures/binary_tree/flatten_binarytree_to_linkedlist.py)
200+
* [Floor And Ceiling](data_structures/binary_tree/floor_and_ceiling.py)
194201
* [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py)
195202
* [Is Bst](data_structures/binary_tree/is_bst.py)
196203
* [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py)
@@ -261,6 +268,7 @@
261268
* [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py)
262269
* [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py)
263270
* [Stack](data_structures/stacks/stack.py)
271+
* [Stack Using Two Queues](data_structures/stacks/stack_using_two_queues.py)
264272
* [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py)
265273
* [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py)
266274
* [Stock Span Problem](data_structures/stacks/stock_span_problem.py)
@@ -334,7 +342,7 @@
334342
* [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py)
335343
* [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py)
336344
* [Longest Palindromic Subsequence](dynamic_programming/longest_palindromic_subsequence.py)
337-
* [Longest Sub Array](dynamic_programming/longest_sub_array.py)
345+
* [Matrix Chain Multiplication](dynamic_programming/matrix_chain_multiplication.py)
338346
* [Matrix Chain Order](dynamic_programming/matrix_chain_order.py)
339347
* [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py)
340348
* [Max Product Subarray](dynamic_programming/max_product_subarray.py)
@@ -357,18 +365,21 @@
357365
* [Trapped Water](dynamic_programming/trapped_water.py)
358366
* [Tribonacci](dynamic_programming/tribonacci.py)
359367
* [Viterbi](dynamic_programming/viterbi.py)
368+
* [Wildcard Matching](dynamic_programming/wildcard_matching.py)
360369
* [Word Break](dynamic_programming/word_break.py)
361370

362371
## Electronics
363372
* [Apparent Power](electronics/apparent_power.py)
364373
* [Builtin Voltage](electronics/builtin_voltage.py)
365374
* [Carrier Concentration](electronics/carrier_concentration.py)
366375
* [Charging Capacitor](electronics/charging_capacitor.py)
376+
* [Charging Inductor](electronics/charging_inductor.py)
367377
* [Circular Convolution](electronics/circular_convolution.py)
368378
* [Coulombs Law](electronics/coulombs_law.py)
369379
* [Electric Conductivity](electronics/electric_conductivity.py)
370380
* [Electric Power](electronics/electric_power.py)
371381
* [Electrical Impedance](electronics/electrical_impedance.py)
382+
* [Ic 555 Timer](electronics/ic_555_timer.py)
372383
* [Ind Reactance](electronics/ind_reactance.py)
373384
* [Ohms Law](electronics/ohms_law.py)
374385
* [Real And Reactive Power](electronics/real_and_reactive_power.py)
@@ -385,6 +396,7 @@
385396

386397
## Financial
387398
* [Equated Monthly Installments](financial/equated_monthly_installments.py)
399+
* [Exponential Moving Average](financial/exponential_moving_average.py)
388400
* [Interest](financial/interest.py)
389401
* [Present Value](financial/present_value.py)
390402
* [Price Plus Tax](financial/price_plus_tax.py)
@@ -475,6 +487,7 @@
475487
* [Fractional Knapsack](greedy_methods/fractional_knapsack.py)
476488
* [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py)
477489
* [Gas Station](greedy_methods/gas_station.py)
490+
* [Minimum Coin Change](greedy_methods/minimum_coin_change.py)
478491
* [Minimum Waiting Time](greedy_methods/minimum_waiting_time.py)
479492
* [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py)
480493

@@ -516,6 +529,7 @@
516529
* [Simplex](linear_programming/simplex.py)
517530

518531
## Machine Learning
532+
* [Apriori Algorithm](machine_learning/apriori_algorithm.py)
519533
* [Astar](machine_learning/astar.py)
520534
* [Data Transformations](machine_learning/data_transformations.py)
521535
* [Decision Tree](machine_learning/decision_tree.py)
@@ -606,7 +620,6 @@
606620
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
607621
* [Germain Primes](maths/germain_primes.py)
608622
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
609-
* [Greedy Coin Change](maths/greedy_coin_change.py)
610623
* [Hamming Numbers](maths/hamming_numbers.py)
611624
* [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py)
612625
* [Harshad Numbers](maths/harshad_numbers.py)
@@ -617,6 +630,7 @@
617630
* [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py)
618631
* [Is Square Free](maths/is_square_free.py)
619632
* [Jaccard Similarity](maths/jaccard_similarity.py)
633+
* [Joint Probability Distribution](maths/joint_probability_distribution.py)
620634
* [Juggler Sequence](maths/juggler_sequence.py)
621635
* [Karatsuba](maths/karatsuba.py)
622636
* [Krishnamurthy Number](maths/krishnamurthy_number.py)
@@ -671,6 +685,7 @@
671685
* [Radix2 Fft](maths/radix2_fft.py)
672686
* [Remove Digit](maths/remove_digit.py)
673687
* [Runge Kutta](maths/runge_kutta.py)
688+
* [Runge Kutta Fehlberg 45](maths/runge_kutta_fehlberg_45.py)
674689
* [Segmented Sieve](maths/segmented_sieve.py)
675690
* Series
676691
* [Arithmetic](maths/series/arithmetic.py)
@@ -688,6 +703,7 @@
688703
* [Sin](maths/sin.py)
689704
* [Sock Merchant](maths/sock_merchant.py)
690705
* [Softmax](maths/softmax.py)
706+
* [Solovay Strassen Primality Test](maths/solovay_strassen_primality_test.py)
691707
* [Square Root](maths/square_root.py)
692708
* [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py)
693709
* [Sum Of Digits](maths/sum_of_digits.py)
@@ -728,6 +744,7 @@
728744
* [Spiral Print](matrix/spiral_print.py)
729745
* Tests
730746
* [Test Matrix Operation](matrix/tests/test_matrix_operation.py)
747+
* [Validate Sudoku Board](matrix/validate_sudoku_board.py)
731748

732749
## Networking Flow
733750
* [Ford Fulkerson](networking_flow/ford_fulkerson.py)
@@ -781,7 +798,7 @@
781798

782799
## Physics
783800
* [Altitude Pressure](physics/altitude_pressure.py)
784-
* [Archimedes Principle](physics/archimedes_principle.py)
801+
* [Archimedes Principle Of Buoyant Force](physics/archimedes_principle_of_buoyant_force.py)
785802
* [Basic Orbital Capture](physics/basic_orbital_capture.py)
786803
* [Casimir Effect](physics/casimir_effect.py)
787804
* [Centripetal Force](physics/centripetal_force.py)
@@ -803,6 +820,7 @@
803820
* [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py)
804821
* [Shear Stress](physics/shear_stress.py)
805822
* [Speed Of Sound](physics/speed_of_sound.py)
823+
* [Speeds Of Gas Molecules](physics/speeds_of_gas_molecules.py)
806824

807825
## Project Euler
808826
* Problem 001
@@ -1106,6 +1124,7 @@
11061124
## Scheduling
11071125
* [First Come First Served](scheduling/first_come_first_served.py)
11081126
* [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py)
1127+
* [Job Sequence With Deadline](scheduling/job_sequence_with_deadline.py)
11091128
* [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py)
11101129
* [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py)
11111130
* [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py)
@@ -1193,6 +1212,7 @@
11931212
* [Capitalize](strings/capitalize.py)
11941213
* [Check Anagrams](strings/check_anagrams.py)
11951214
* [Credit Card Validator](strings/credit_card_validator.py)
1215+
* [Damerau Levenshtein Distance](strings/damerau_levenshtein_distance.py)
11961216
* [Detecting English Programmatically](strings/detecting_english_programmatically.py)
11971217
* [Dna](strings/dna.py)
11981218
* [Frequency Finder](strings/frequency_finder.py)
@@ -1225,6 +1245,7 @@
12251245
* [String Switch Case](strings/string_switch_case.py)
12261246
* [Strip](strings/strip.py)
12271247
* [Text Justification](strings/text_justification.py)
1248+
* [Title](strings/title.py)
12281249
* [Top K Frequent Words](strings/top_k_frequent_words.py)
12291250
* [Upper](strings/upper.py)
12301251
* [Wave](strings/wave.py)

arithmetic_analysis/lu_decomposition.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,15 +88,19 @@ def lower_upper_decomposition(table: np.ndarray) -> tuple[np.ndarray, np.ndarray
8888

8989
lower = np.zeros((rows, columns))
9090
upper = np.zeros((rows, columns))
91+
92+
# in 'total', the necessary data is extracted through slices
93+
# and the sum of the products is obtained.
94+
9195
for i in range(columns):
9296
for j in range(i):
93-
total = sum(lower[i][k] * upper[k][j] for k in range(j))
97+
total = np.sum(lower[i, :i] * upper[:i, j])
9498
if upper[j][j] == 0:
9599
raise ArithmeticError("No LU decomposition exists")
96100
lower[i][j] = (table[i][j] - total) / upper[j][j]
97101
lower[i][i] = 1
98102
for j in range(i, columns):
99-
total = sum(lower[i][k] * upper[k][j] for k in range(j))
103+
total = np.sum(lower[i, :i] * upper[:i, j])
100104
upper[i][j] = table[i][j] - total
101105
return lower, upper
102106

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

bit_manipulation/count_number_of_one_bits.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,13 @@ def do_benchmark(number: int) -> None:
7070
setup = "import __main__ as z"
7171
print(f"Benchmark when {number = }:")
7272
print(f"{get_set_bits_count_using_modulo_operator(number) = }")
73-
timing = timeit("z.get_set_bits_count_using_modulo_operator(25)", setup=setup)
73+
timing = timeit(
74+
f"z.get_set_bits_count_using_modulo_operator({number})", setup=setup
75+
)
7476
print(f"timeit() runs in {timing} seconds")
7577
print(f"{get_set_bits_count_using_brian_kernighans_algorithm(number) = }")
7678
timing = timeit(
77-
"z.get_set_bits_count_using_brian_kernighans_algorithm(25)",
79+
f"z.get_set_bits_count_using_brian_kernighans_algorithm({number})",
7880
setup=setup,
7981
)
8082
print(f"timeit() runs in {timing} seconds")

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

boolean_algebra/and_gate.py

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -29,22 +29,10 @@ def and_gate(input_1: int, input_2: int) -> int:
2929
>>> and_gate(1, 1)
3030
1
3131
"""
32-
return int((input_1, input_2).count(0) == 0)
33-
34-
35-
def test_and_gate() -> None:
36-
"""
37-
Tests the and_gate function
38-
"""
39-
assert and_gate(0, 0) == 0
40-
assert and_gate(0, 1) == 0
41-
assert and_gate(1, 0) == 0
42-
assert and_gate(1, 1) == 1
32+
return int(input_1 and input_2)
4333

4434

4535
if __name__ == "__main__":
46-
test_and_gate()
47-
print(and_gate(1, 0))
48-
print(and_gate(0, 0))
49-
print(and_gate(0, 1))
50-
print(and_gate(1, 1))
36+
import doctest
37+
38+
doctest.testmod()

boolean_algebra/imply_gate.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ def imply_gate(input_1: int, input_2: int) -> int:
3434

3535

3636
if __name__ == "__main__":
37-
print(imply_gate(0, 0))
38-
print(imply_gate(0, 1))
39-
print(imply_gate(1, 0))
40-
print(imply_gate(1, 1))
37+
import doctest
38+
39+
doctest.testmod()

0 commit comments

Comments
 (0)