Skip to content

Commit 578728f

Browse files
authored
Merge branch 'TheAlgorithms:master' into terminal_velocity
2 parents 9c637ad + 788e4ed commit 578728f

File tree

69 files changed

+3406
-440
lines changed

Some content is hidden

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

69 files changed

+3406
-440
lines changed

Diff for: .github/ISSUE_TEMPLATE/feature_request.yml

+2-2
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

Diff for: .pre-commit-config.yaml

+1-1
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

Diff for: DIRECTORY.md

+25-4
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)

Diff for: arithmetic_analysis/lu_decomposition.py

+6-2
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

Diff for: backtracking/all_combinations.py

+38-9
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,40 @@
11
"""
22
In this problem, we want to determine all possible combinations of k
33
numbers out of 1 ... n. We use backtracking to solve this problem.
4-
Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
4+
5+
Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))),
56
"""
67
from __future__ import annotations
78

9+
from itertools import combinations
10+
11+
12+
def combination_lists(n: int, k: int) -> list[list[int]]:
13+
"""
14+
>>> combination_lists(n=4, k=2)
15+
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
16+
"""
17+
return [list(x) for x in combinations(range(1, n + 1), k)]
18+
819

920
def generate_all_combinations(n: int, k: int) -> list[list[int]]:
1021
"""
1122
>>> generate_all_combinations(n=4, k=2)
1223
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
24+
>>> generate_all_combinations(n=0, k=0)
25+
[[]]
26+
>>> generate_all_combinations(n=10, k=-1)
27+
Traceback (most recent call last):
28+
...
29+
RecursionError: maximum recursion depth exceeded
30+
>>> generate_all_combinations(n=-1, k=10)
31+
[]
32+
>>> generate_all_combinations(n=5, k=4)
33+
[[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]]
34+
>>> from itertools import combinations
35+
>>> all(generate_all_combinations(n, k) == combination_lists(n, k)
36+
... for n in range(1, 6) for k in range(1, 6))
37+
True
1338
"""
1439

1540
result: list[list[int]] = []
@@ -34,13 +59,17 @@ def create_all_state(
3459
current_list.pop()
3560

3661

37-
def print_all_state(total_list: list[list[int]]) -> None:
38-
for i in total_list:
39-
print(*i)
62+
if __name__ == "__main__":
63+
from doctest import testmod
4064

65+
testmod()
66+
print(generate_all_combinations(n=4, k=2))
67+
tests = ((n, k) for n in range(1, 5) for k in range(1, 5))
68+
for n, k in tests:
69+
print(n, k, generate_all_combinations(n, k) == combination_lists(n, k))
4170

42-
if __name__ == "__main__":
43-
n = 4
44-
k = 2
45-
total_list = generate_all_combinations(n, k)
46-
print_all_state(total_list)
71+
print("Benchmark:")
72+
from timeit import timeit
73+
74+
for func in ("combination_lists", "generate_all_combinations"):
75+
print(f"{func:>25}(): {timeit(f'{func}(n=4, k = 2)', globals=globals())}")

Diff for: backtracking/power_sum.py

+20-22
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

0 commit comments

Comments
 (0)