Skip to content

Commit e4927c3

Browse files
Merge branch 'master' into rtang09-patch-3
2 parents d0bc97f + 572de4f commit e4927c3

File tree

102 files changed

+4281
-713
lines changed

Some content is hidden

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

102 files changed

+4281
-713
lines changed

.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

.pre-commit-config.yaml

+2-2
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,12 @@ 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

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

+26-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)
@@ -532,6 +546,7 @@
532546
* [Logistic Regression](machine_learning/logistic_regression.py)
533547
* Loss Functions
534548
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
549+
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
535550
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
536551
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
537552
* [Mfcc](machine_learning/mfcc.py)
@@ -605,7 +620,6 @@
605620
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
606621
* [Germain Primes](maths/germain_primes.py)
607622
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
608-
* [Greedy Coin Change](maths/greedy_coin_change.py)
609623
* [Hamming Numbers](maths/hamming_numbers.py)
610624
* [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py)
611625
* [Harshad Numbers](maths/harshad_numbers.py)
@@ -616,6 +630,7 @@
616630
* [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py)
617631
* [Is Square Free](maths/is_square_free.py)
618632
* [Jaccard Similarity](maths/jaccard_similarity.py)
633+
* [Joint Probability Distribution](maths/joint_probability_distribution.py)
619634
* [Juggler Sequence](maths/juggler_sequence.py)
620635
* [Karatsuba](maths/karatsuba.py)
621636
* [Krishnamurthy Number](maths/krishnamurthy_number.py)
@@ -670,6 +685,7 @@
670685
* [Radix2 Fft](maths/radix2_fft.py)
671686
* [Remove Digit](maths/remove_digit.py)
672687
* [Runge Kutta](maths/runge_kutta.py)
688+
* [Runge Kutta Fehlberg 45](maths/runge_kutta_fehlberg_45.py)
673689
* [Segmented Sieve](maths/segmented_sieve.py)
674690
* Series
675691
* [Arithmetic](maths/series/arithmetic.py)
@@ -687,6 +703,7 @@
687703
* [Sin](maths/sin.py)
688704
* [Sock Merchant](maths/sock_merchant.py)
689705
* [Softmax](maths/softmax.py)
706+
* [Solovay Strassen Primality Test](maths/solovay_strassen_primality_test.py)
690707
* [Square Root](maths/square_root.py)
691708
* [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py)
692709
* [Sum Of Digits](maths/sum_of_digits.py)
@@ -727,6 +744,7 @@
727744
* [Spiral Print](matrix/spiral_print.py)
728745
* Tests
729746
* [Test Matrix Operation](matrix/tests/test_matrix_operation.py)
747+
* [Validate Sudoku Board](matrix/validate_sudoku_board.py)
730748

731749
## Networking Flow
732750
* [Ford Fulkerson](networking_flow/ford_fulkerson.py)
@@ -780,7 +798,7 @@
780798

781799
## Physics
782800
* [Altitude Pressure](physics/altitude_pressure.py)
783-
* [Archimedes Principle](physics/archimedes_principle.py)
801+
* [Archimedes Principle Of Buoyant Force](physics/archimedes_principle_of_buoyant_force.py)
784802
* [Basic Orbital Capture](physics/basic_orbital_capture.py)
785803
* [Casimir Effect](physics/casimir_effect.py)
786804
* [Centripetal Force](physics/centripetal_force.py)
@@ -802,6 +820,7 @@
802820
* [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py)
803821
* [Shear Stress](physics/shear_stress.py)
804822
* [Speed Of Sound](physics/speed_of_sound.py)
823+
* [Speeds Of Gas Molecules](physics/speeds_of_gas_molecules.py)
805824

806825
## Project Euler
807826
* Problem 001
@@ -1105,6 +1124,7 @@
11051124
## Scheduling
11061125
* [First Come First Served](scheduling/first_come_first_served.py)
11071126
* [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py)
1127+
* [Job Sequence With Deadline](scheduling/job_sequence_with_deadline.py)
11081128
* [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py)
11091129
* [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py)
11101130
* [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py)
@@ -1192,6 +1212,7 @@
11921212
* [Capitalize](strings/capitalize.py)
11931213
* [Check Anagrams](strings/check_anagrams.py)
11941214
* [Credit Card Validator](strings/credit_card_validator.py)
1215+
* [Damerau Levenshtein Distance](strings/damerau_levenshtein_distance.py)
11951216
* [Detecting English Programmatically](strings/detecting_english_programmatically.py)
11961217
* [Dna](strings/dna.py)
11971218
* [Frequency Finder](strings/frequency_finder.py)
@@ -1224,6 +1245,7 @@
12241245
* [String Switch Case](strings/string_switch_case.py)
12251246
* [Strip](strings/strip.py)
12261247
* [Text Justification](strings/text_justification.py)
1248+
* [Title](strings/title.py)
12271249
* [Top K Frequent Words](strings/top_k_frequent_words.py)
12281250
* [Upper](strings/upper.py)
12291251
* [Wave](strings/wave.py)

arithmetic_analysis/gaussian_elimination.py

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

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

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())}")

0 commit comments

Comments
 (0)