Skip to content

Commit 1b1b983

Browse files
authored
Merge branch 'TheAlgorithms:master' into time_period_simple_pendulum
2 parents 9717c31 + abc3909 commit 1b1b983

Some content is hidden

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

61 files changed

+2920
-1197
lines changed

.github/pull_request_template.md

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
* [ ] Add an algorithm?
66
* [ ] Fix a bug or typo in an existing algorithm?
7+
* [ ] Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
78
* [ ] Documentation change?
89

910
### Checklist:

DIRECTORY.md

+35-28
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737

3838
## Bit Manipulation
3939
* [Binary And Operator](bit_manipulation/binary_and_operator.py)
40+
* [Binary Coded Decimal](bit_manipulation/binary_coded_decimal.py)
4041
* [Binary Count Setbits](bit_manipulation/binary_count_setbits.py)
4142
* [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py)
4243
* [Binary Or Operator](bit_manipulation/binary_or_operator.py)
@@ -57,6 +58,7 @@
5758
* [Power Of 4](bit_manipulation/power_of_4.py)
5859
* [Reverse Bits](bit_manipulation/reverse_bits.py)
5960
* [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py)
61+
* [Swap All Odd And Even Bits](bit_manipulation/swap_all_odd_and_even_bits.py)
6062

6163
## Blockchain
6264
* [Diophantine Equation](blockchain/diophantine_equation.py)
@@ -124,6 +126,7 @@
124126
* [Transposition Cipher](ciphers/transposition_cipher.py)
125127
* [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py)
126128
* [Trifid Cipher](ciphers/trifid_cipher.py)
129+
* [Vernam Cipher](ciphers/vernam_cipher.py)
127130
* [Vigenere Cipher](ciphers/vigenere_cipher.py)
128131
* [Xor Cipher](ciphers/xor_cipher.py)
129132

@@ -163,13 +166,15 @@
163166
* [Molecular Chemistry](conversions/molecular_chemistry.py)
164167
* [Octal To Binary](conversions/octal_to_binary.py)
165168
* [Octal To Decimal](conversions/octal_to_decimal.py)
169+
* [Octal To Hexadecimal](conversions/octal_to_hexadecimal.py)
166170
* [Prefix Conversions](conversions/prefix_conversions.py)
167171
* [Prefix Conversions String](conversions/prefix_conversions_string.py)
168172
* [Pressure Conversions](conversions/pressure_conversions.py)
169173
* [Rgb Hsv Conversion](conversions/rgb_hsv_conversion.py)
170174
* [Roman Numerals](conversions/roman_numerals.py)
171175
* [Speed Conversions](conversions/speed_conversions.py)
172176
* [Temperature Conversions](conversions/temperature_conversions.py)
177+
* [Time Conversions](conversions/time_conversions.py)
173178
* [Volume Conversions](conversions/volume_conversions.py)
174179
* [Weight Conversion](conversions/weight_conversion.py)
175180

@@ -183,6 +188,7 @@
183188
* [Prefix Sum](data_structures/arrays/prefix_sum.py)
184189
* [Product Sum](data_structures/arrays/product_sum.py)
185190
* [Sparse Table](data_structures/arrays/sparse_table.py)
191+
* [Sudoku Solver](data_structures/arrays/sudoku_solver.py)
186192
* Binary Tree
187193
* [Avl Tree](data_structures/binary_tree/avl_tree.py)
188194
* [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py)
@@ -199,7 +205,8 @@
199205
* [Flatten Binarytree To Linkedlist](data_structures/binary_tree/flatten_binarytree_to_linkedlist.py)
200206
* [Floor And Ceiling](data_structures/binary_tree/floor_and_ceiling.py)
201207
* [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py)
202-
* [Is Bst](data_structures/binary_tree/is_bst.py)
208+
* [Is Sorted](data_structures/binary_tree/is_sorted.py)
209+
* [Is Sum Tree](data_structures/binary_tree/is_sum_tree.py)
203210
* [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py)
204211
* [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py)
205212
* [Maximum Fenwick Tree](data_structures/binary_tree/maximum_fenwick_tree.py)
@@ -432,8 +439,7 @@
432439
* [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py)
433440
* [Breadth First Search Shortest Path 2](graphs/breadth_first_search_shortest_path_2.py)
434441
* [Breadth First Search Zero One Shortest Path](graphs/breadth_first_search_zero_one_shortest_path.py)
435-
* [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py)
436-
* [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py)
442+
* [Check Bipatrite](graphs/check_bipatrite.py)
437443
* [Check Cycle](graphs/check_cycle.py)
438444
* [Connected Components](graphs/connected_components.py)
439445
* [Deep Clone Graph](graphs/deep_clone_graph.py)
@@ -536,6 +542,7 @@
536542
* [Dimensionality Reduction](machine_learning/dimensionality_reduction.py)
537543
* Forecasting
538544
* [Run](machine_learning/forecasting/run.py)
545+
* [Frequent Pattern Growth](machine_learning/frequent_pattern_growth.py)
539546
* [Gradient Descent](machine_learning/gradient_descent.py)
540547
* [K Means Clust](machine_learning/k_means_clust.py)
541548
* [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py)
@@ -544,11 +551,7 @@
544551
* Local Weighted Learning
545552
* [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py)
546553
* [Logistic Regression](machine_learning/logistic_regression.py)
547-
* Loss Functions
548-
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
549-
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
550-
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
551-
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
554+
* [Loss Functions](machine_learning/loss_functions.py)
552555
* [Mfcc](machine_learning/mfcc.py)
553556
* [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py)
554557
* [Polynomial Regression](machine_learning/polynomial_regression.py)
@@ -569,25 +572,18 @@
569572
* [Arc Length](maths/arc_length.py)
570573
* [Area](maths/area.py)
571574
* [Area Under Curve](maths/area_under_curve.py)
572-
* [Armstrong Numbers](maths/armstrong_numbers.py)
573-
* [Automorphic Number](maths/automorphic_number.py)
574575
* [Average Absolute Deviation](maths/average_absolute_deviation.py)
575576
* [Average Mean](maths/average_mean.py)
576577
* [Average Median](maths/average_median.py)
577578
* [Average Mode](maths/average_mode.py)
578579
* [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py)
579580
* [Base Neg2 Conversion](maths/base_neg2_conversion.py)
580581
* [Basic Maths](maths/basic_maths.py)
581-
* [Bell Numbers](maths/bell_numbers.py)
582-
* [Binary Exp Mod](maths/binary_exp_mod.py)
583582
* [Binary Exponentiation](maths/binary_exponentiation.py)
584-
* [Binary Exponentiation 2](maths/binary_exponentiation_2.py)
585583
* [Binary Multiplication](maths/binary_multiplication.py)
586584
* [Binomial Coefficient](maths/binomial_coefficient.py)
587585
* [Binomial Distribution](maths/binomial_distribution.py)
588586
* [Bisection](maths/bisection.py)
589-
* [Carmichael Number](maths/carmichael_number.py)
590-
* [Catalan Number](maths/catalan_number.py)
591587
* [Ceil](maths/ceil.py)
592588
* [Chebyshev Distance](maths/chebyshev_distance.py)
593589
* [Check Polygon](maths/check_polygon.py)
@@ -620,10 +616,7 @@
620616
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
621617
* [Germain Primes](maths/germain_primes.py)
622618
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
623-
* [Hamming Numbers](maths/hamming_numbers.py)
624619
* [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py)
625-
* [Harshad Numbers](maths/harshad_numbers.py)
626-
* [Hexagonal Number](maths/hexagonal_number.py)
627620
* [Integration By Simpson Approx](maths/integration_by_simpson_approx.py)
628621
* [Interquartile Range](maths/interquartile_range.py)
629622
* [Is Int Palindrome](maths/is_int_palindrome.py)
@@ -633,7 +626,6 @@
633626
* [Joint Probability Distribution](maths/joint_probability_distribution.py)
634627
* [Juggler Sequence](maths/juggler_sequence.py)
635628
* [Karatsuba](maths/karatsuba.py)
636-
* [Krishnamurthy Number](maths/krishnamurthy_number.py)
637629
* [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py)
638630
* [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py)
639631
* [Least Common Multiple](maths/least_common_multiple.py)
@@ -665,7 +657,6 @@
665657
* [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py)
666658
* [Points Are Collinear 3D](maths/points_are_collinear_3d.py)
667659
* [Pollard Rho](maths/pollard_rho.py)
668-
* [Polygonal Numbers](maths/polygonal_numbers.py)
669660
* [Polynomial Evaluation](maths/polynomial_evaluation.py)
670661
* Polynomials
671662
* [Single Indeterminate Operations](maths/polynomials/single_indeterminate_operations.py)
@@ -676,8 +667,6 @@
676667
* [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py)
677668
* [Primelib](maths/primelib.py)
678669
* [Print Multiplication Table](maths/print_multiplication_table.py)
679-
* [Pronic Number](maths/pronic_number.py)
680-
* [Proth Number](maths/proth_number.py)
681670
* [Pythagoras](maths/pythagoras.py)
682671
* [Qr Decomposition](maths/qr_decomposition.py)
683672
* [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py)
@@ -704,6 +693,22 @@
704693
* [Sock Merchant](maths/sock_merchant.py)
705694
* [Softmax](maths/softmax.py)
706695
* [Solovay Strassen Primality Test](maths/solovay_strassen_primality_test.py)
696+
* Special Numbers
697+
* [Armstrong Numbers](maths/special_numbers/armstrong_numbers.py)
698+
* [Automorphic Number](maths/special_numbers/automorphic_number.py)
699+
* [Bell Numbers](maths/special_numbers/bell_numbers.py)
700+
* [Carmichael Number](maths/special_numbers/carmichael_number.py)
701+
* [Catalan Number](maths/special_numbers/catalan_number.py)
702+
* [Hamming Numbers](maths/special_numbers/hamming_numbers.py)
703+
* [Harshad Numbers](maths/special_numbers/harshad_numbers.py)
704+
* [Hexagonal Number](maths/special_numbers/hexagonal_number.py)
705+
* [Krishnamurthy Number](maths/special_numbers/krishnamurthy_number.py)
706+
* [Perfect Number](maths/special_numbers/perfect_number.py)
707+
* [Polygonal Numbers](maths/special_numbers/polygonal_numbers.py)
708+
* [Pronic Number](maths/special_numbers/pronic_number.py)
709+
* [Proth Number](maths/special_numbers/proth_number.py)
710+
* [Ugly Numbers](maths/special_numbers/ugly_numbers.py)
711+
* [Weird Number](maths/special_numbers/weird_number.py)
707712
* [Square Root](maths/square_root.py)
708713
* [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py)
709714
* [Sum Of Digits](maths/sum_of_digits.py)
@@ -719,9 +724,7 @@
719724
* [Twin Prime](maths/twin_prime.py)
720725
* [Two Pointer](maths/two_pointer.py)
721726
* [Two Sum](maths/two_sum.py)
722-
* [Ugly Numbers](maths/ugly_numbers.py)
723727
* [Volume](maths/volume.py)
724-
* [Weird Number](maths/weird_number.py)
725728
* [Zellers Congruence](maths/zellers_congruence.py)
726729

727730
## Matrix
@@ -733,6 +736,7 @@
733736
* [Inverse Of Matrix](matrix/inverse_of_matrix.py)
734737
* [Largest Square Area In Matrix](matrix/largest_square_area_in_matrix.py)
735738
* [Matrix Class](matrix/matrix_class.py)
739+
* [Matrix Multiplication Recursion](matrix/matrix_multiplication_recursion.py)
736740
* [Matrix Operation](matrix/matrix_operation.py)
737741
* [Max Area Of Island](matrix/max_area_of_island.py)
738742
* [Median Matrix](matrix/median_matrix.py)
@@ -759,19 +763,18 @@
759763
* [Mish](neural_network/activation_functions/mish.py)
760764
* [Rectified Linear Unit](neural_network/activation_functions/rectified_linear_unit.py)
761765
* [Scaled Exponential Linear Unit](neural_network/activation_functions/scaled_exponential_linear_unit.py)
762-
* [Sigmoid Linear Unit](neural_network/activation_functions/sigmoid_linear_unit.py)
763766
* [Soboleva Modified Hyperbolic Tangent](neural_network/activation_functions/soboleva_modified_hyperbolic_tangent.py)
764767
* [Softplus](neural_network/activation_functions/softplus.py)
765768
* [Squareplus](neural_network/activation_functions/squareplus.py)
769+
* [Swish](neural_network/activation_functions/swish.py)
766770
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
767771
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
768-
* [Perceptron](neural_network/perceptron.py)
769772
* [Simple Neural Network](neural_network/simple_neural_network.py)
770773

771774
## Other
772775
* [Activity Selection](other/activity_selection.py)
773776
* [Alternative List Arrange](other/alternative_list_arrange.py)
774-
* [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py)
777+
* [Davis Putnam Logemann Loveland](other/davis_putnam_logemann_loveland.py)
775778
* [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py)
776779
* [Doomsday](other/doomsday.py)
777780
* [Fischer Yates Shuffle](other/fischer_yates_shuffle.py)
@@ -801,15 +804,18 @@
801804
* [Archimedes Principle Of Buoyant Force](physics/archimedes_principle_of_buoyant_force.py)
802805
* [Basic Orbital Capture](physics/basic_orbital_capture.py)
803806
* [Casimir Effect](physics/casimir_effect.py)
807+
* [Center Of Mass](physics/center_of_mass.py)
804808
* [Centripetal Force](physics/centripetal_force.py)
805809
* [Coulombs Law](physics/coulombs_law.py)
810+
* [Doppler Frequency](physics/doppler_frequency.py)
806811
* [Grahams Law](physics/grahams_law.py)
807812
* [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py)
808813
* [Hubble Parameter](physics/hubble_parameter.py)
809814
* [Ideal Gas Law](physics/ideal_gas_law.py)
810815
* [Kinetic Energy](physics/kinetic_energy.py)
811816
* [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py)
812817
* [Malus Law](physics/malus_law.py)
818+
* [Mass Energy Equivalence](physics/mass_energy_equivalence.py)
813819
* [Mirror Formulae](physics/mirror_formulae.py)
814820
* [N Body Simulation](physics/n_body_simulation.py)
815821
* [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py)
@@ -1184,7 +1190,6 @@
11841190
* [Quick Sort](sorts/quick_sort.py)
11851191
* [Quick Sort 3 Partition](sorts/quick_sort_3_partition.py)
11861192
* [Radix Sort](sorts/radix_sort.py)
1187-
* [Recursive Bubble Sort](sorts/recursive_bubble_sort.py)
11881193
* [Recursive Insertion Sort](sorts/recursive_insertion_sort.py)
11891194
* [Recursive Mergesort Array](sorts/recursive_mergesort_array.py)
11901195
* [Recursive Quick Sort](sorts/recursive_quick_sort.py)
@@ -1215,12 +1220,14 @@
12151220
* [Damerau Levenshtein Distance](strings/damerau_levenshtein_distance.py)
12161221
* [Detecting English Programmatically](strings/detecting_english_programmatically.py)
12171222
* [Dna](strings/dna.py)
1223+
* [Edit Distance](strings/edit_distance.py)
12181224
* [Frequency Finder](strings/frequency_finder.py)
12191225
* [Hamming Distance](strings/hamming_distance.py)
12201226
* [Indian Phone Validator](strings/indian_phone_validator.py)
12211227
* [Is Contains Unique Chars](strings/is_contains_unique_chars.py)
12221228
* [Is Isogram](strings/is_isogram.py)
12231229
* [Is Pangram](strings/is_pangram.py)
1230+
* [Is Polish National Id](strings/is_polish_national_id.py)
12241231
* [Is Spain National Id](strings/is_spain_national_id.py)
12251232
* [Is Srilankan Phone Number](strings/is_srilankan_phone_number.py)
12261233
* [Is Valid Email Address](strings/is_valid_email_address.py)

backtracking/n_queens.py

+26-27
Original file line numberDiff line numberDiff line change
@@ -17,50 +17,49 @@ def is_safe(board: list[list[int]], row: int, column: int) -> bool:
1717
This function returns a boolean value True if it is safe to place a queen there
1818
considering the current state of the board.
1919
20-
Parameters :
21-
board(2D matrix) : board
22-
row ,column : coordinates of the cell on a board
20+
Parameters:
21+
board (2D matrix): The chessboard
22+
row, column: Coordinates of the cell on the board
2323
24-
Returns :
24+
Returns:
2525
Boolean Value
2626
2727
"""
28-
for i in range(len(board)):
29-
if board[row][i] == 1:
30-
return False
31-
for i in range(len(board)):
32-
if board[i][column] == 1:
33-
return False
34-
for i, j in zip(range(row, -1, -1), range(column, -1, -1)):
35-
if board[i][j] == 1:
36-
return False
37-
for i, j in zip(range(row, -1, -1), range(column, len(board))):
38-
if board[i][j] == 1:
39-
return False
40-
return True
28+
29+
n = len(board) # Size of the board
30+
31+
# Check if there is any queen in the same row, column,
32+
# left upper diagonal, and right upper diagonal
33+
return (
34+
all(board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, n)))
35+
and all(
36+
board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, -1, -1))
37+
)
38+
and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, n)))
39+
and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, -1, -1)))
40+
)
4141

4242

4343
def solve(board: list[list[int]], row: int) -> bool:
4444
"""
45-
It creates a state space tree and calls the safe function until it receives a
46-
False Boolean and terminates that branch and backtracks to the next
45+
This function creates a state space tree and calls the safe function until it
46+
receives a False Boolean and terminates that branch and backtracks to the next
4747
possible solution branch.
4848
"""
4949
if row >= len(board):
5050
"""
51-
If the row number exceeds N we have board with a successful combination
51+
If the row number exceeds N, we have a board with a successful combination
5252
and that combination is appended to the solution list and the board is printed.
53-
5453
"""
5554
solution.append(board)
5655
printboard(board)
5756
print()
5857
return True
5958
for i in range(len(board)):
6059
"""
61-
For every row it iterates through each column to check if it is feasible to
60+
For every row, it iterates through each column to check if it is feasible to
6261
place a queen there.
63-
If all the combinations for that particular branch are successful the board is
62+
If all the combinations for that particular branch are successful, the board is
6463
reinitialized for the next possible combination.
6564
"""
6665
if is_safe(board, row, i):
@@ -77,14 +76,14 @@ def printboard(board: list[list[int]]) -> None:
7776
for i in range(len(board)):
7877
for j in range(len(board)):
7978
if board[i][j] == 1:
80-
print("Q", end=" ")
79+
print("Q", end=" ") # Queen is present
8180
else:
82-
print(".", end=" ")
81+
print(".", end=" ") # Empty cell
8382
print()
8483

8584

86-
# n=int(input("The no. of queens"))
85+
# Number of queens (e.g., n=8 for an 8x8 board)
8786
n = 8
8887
board = [[0 for i in range(n)] for j in range(n)]
8988
solve(board, 0)
90-
print("The total no. of solutions are :", len(solution))
89+
print("The total number of solutions are:", len(solution))

0 commit comments

Comments
 (0)