Skip to content

Commit cfaec83

Browse files
authored
Merge branch 'TheAlgorithms:master' into master
2 parents 712f4c0 + fdb0635 commit cfaec83

Some content is hidden

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

48 files changed

+2277
-1133
lines changed

DIRECTORY.md

Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@
174174
* [Roman Numerals](conversions/roman_numerals.py)
175175
* [Speed Conversions](conversions/speed_conversions.py)
176176
* [Temperature Conversions](conversions/temperature_conversions.py)
177+
* [Time Conversions](conversions/time_conversions.py)
177178
* [Volume Conversions](conversions/volume_conversions.py)
178179
* [Weight Conversion](conversions/weight_conversion.py)
179180

@@ -438,8 +439,7 @@
438439
* [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py)
439440
* [Breadth First Search Shortest Path 2](graphs/breadth_first_search_shortest_path_2.py)
440441
* [Breadth First Search Zero One Shortest Path](graphs/breadth_first_search_zero_one_shortest_path.py)
441-
* [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py)
442-
* [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py)
442+
* [Check Bipatrite](graphs/check_bipatrite.py)
443443
* [Check Cycle](graphs/check_cycle.py)
444444
* [Connected Components](graphs/connected_components.py)
445445
* [Deep Clone Graph](graphs/deep_clone_graph.py)
@@ -542,6 +542,7 @@
542542
* [Dimensionality Reduction](machine_learning/dimensionality_reduction.py)
543543
* Forecasting
544544
* [Run](machine_learning/forecasting/run.py)
545+
* [Frequent Pattern Growth](machine_learning/frequent_pattern_growth.py)
545546
* [Gradient Descent](machine_learning/gradient_descent.py)
546547
* [K Means Clust](machine_learning/k_means_clust.py)
547548
* [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py)
@@ -550,13 +551,7 @@
550551
* Local Weighted Learning
551552
* [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py)
552553
* [Logistic Regression](machine_learning/logistic_regression.py)
553-
* Loss Functions
554-
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
555-
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
556-
* [Hinge Loss](machine_learning/loss_functions/hinge_loss.py)
557-
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
558-
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
559-
* [Mean Squared Logarithmic Error](machine_learning/loss_functions/mean_squared_logarithmic_error.py)
554+
* [Loss Functions](machine_learning/loss_functions.py)
560555
* [Mfcc](machine_learning/mfcc.py)
561556
* [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py)
562557
* [Polynomial Regression](machine_learning/polynomial_regression.py)
@@ -577,25 +572,18 @@
577572
* [Arc Length](maths/arc_length.py)
578573
* [Area](maths/area.py)
579574
* [Area Under Curve](maths/area_under_curve.py)
580-
* [Armstrong Numbers](maths/armstrong_numbers.py)
581-
* [Automorphic Number](maths/automorphic_number.py)
582575
* [Average Absolute Deviation](maths/average_absolute_deviation.py)
583576
* [Average Mean](maths/average_mean.py)
584577
* [Average Median](maths/average_median.py)
585578
* [Average Mode](maths/average_mode.py)
586579
* [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py)
587580
* [Base Neg2 Conversion](maths/base_neg2_conversion.py)
588581
* [Basic Maths](maths/basic_maths.py)
589-
* [Bell Numbers](maths/bell_numbers.py)
590-
* [Binary Exp Mod](maths/binary_exp_mod.py)
591582
* [Binary Exponentiation](maths/binary_exponentiation.py)
592-
* [Binary Exponentiation 2](maths/binary_exponentiation_2.py)
593583
* [Binary Multiplication](maths/binary_multiplication.py)
594584
* [Binomial Coefficient](maths/binomial_coefficient.py)
595585
* [Binomial Distribution](maths/binomial_distribution.py)
596586
* [Bisection](maths/bisection.py)
597-
* [Carmichael Number](maths/carmichael_number.py)
598-
* [Catalan Number](maths/catalan_number.py)
599587
* [Ceil](maths/ceil.py)
600588
* [Chebyshev Distance](maths/chebyshev_distance.py)
601589
* [Check Polygon](maths/check_polygon.py)
@@ -628,10 +616,7 @@
628616
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
629617
* [Germain Primes](maths/germain_primes.py)
630618
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
631-
* [Hamming Numbers](maths/hamming_numbers.py)
632619
* [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py)
633-
* [Harshad Numbers](maths/harshad_numbers.py)
634-
* [Hexagonal Number](maths/hexagonal_number.py)
635620
* [Integration By Simpson Approx](maths/integration_by_simpson_approx.py)
636621
* [Interquartile Range](maths/interquartile_range.py)
637622
* [Is Int Palindrome](maths/is_int_palindrome.py)
@@ -641,7 +626,6 @@
641626
* [Joint Probability Distribution](maths/joint_probability_distribution.py)
642627
* [Juggler Sequence](maths/juggler_sequence.py)
643628
* [Karatsuba](maths/karatsuba.py)
644-
* [Krishnamurthy Number](maths/krishnamurthy_number.py)
645629
* [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py)
646630
* [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py)
647631
* [Least Common Multiple](maths/least_common_multiple.py)
@@ -673,7 +657,6 @@
673657
* [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py)
674658
* [Points Are Collinear 3D](maths/points_are_collinear_3d.py)
675659
* [Pollard Rho](maths/pollard_rho.py)
676-
* [Polygonal Numbers](maths/polygonal_numbers.py)
677660
* [Polynomial Evaluation](maths/polynomial_evaluation.py)
678661
* Polynomials
679662
* [Single Indeterminate Operations](maths/polynomials/single_indeterminate_operations.py)
@@ -684,8 +667,6 @@
684667
* [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py)
685668
* [Primelib](maths/primelib.py)
686669
* [Print Multiplication Table](maths/print_multiplication_table.py)
687-
* [Pronic Number](maths/pronic_number.py)
688-
* [Proth Number](maths/proth_number.py)
689670
* [Pythagoras](maths/pythagoras.py)
690671
* [Qr Decomposition](maths/qr_decomposition.py)
691672
* [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py)
@@ -712,6 +693,22 @@
712693
* [Sock Merchant](maths/sock_merchant.py)
713694
* [Softmax](maths/softmax.py)
714695
* [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)
715712
* [Square Root](maths/square_root.py)
716713
* [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py)
717714
* [Sum Of Digits](maths/sum_of_digits.py)
@@ -727,9 +724,7 @@
727724
* [Twin Prime](maths/twin_prime.py)
728725
* [Two Pointer](maths/two_pointer.py)
729726
* [Two Sum](maths/two_sum.py)
730-
* [Ugly Numbers](maths/ugly_numbers.py)
731727
* [Volume](maths/volume.py)
732-
* [Weird Number](maths/weird_number.py)
733728
* [Zellers Congruence](maths/zellers_congruence.py)
734729

735730
## Matrix
@@ -774,13 +769,12 @@
774769
* [Swish](neural_network/activation_functions/swish.py)
775770
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
776771
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
777-
* [Perceptron](neural_network/perceptron.py)
778772
* [Simple Neural Network](neural_network/simple_neural_network.py)
779773

780774
## Other
781775
* [Activity Selection](other/activity_selection.py)
782776
* [Alternative List Arrange](other/alternative_list_arrange.py)
783-
* [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py)
777+
* [Davis Putnam Logemann Loveland](other/davis_putnam_logemann_loveland.py)
784778
* [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py)
785779
* [Doomsday](other/doomsday.py)
786780
* [Fischer Yates Shuffle](other/fischer_yates_shuffle.py)
@@ -810,8 +804,10 @@
810804
* [Archimedes Principle Of Buoyant Force](physics/archimedes_principle_of_buoyant_force.py)
811805
* [Basic Orbital Capture](physics/basic_orbital_capture.py)
812806
* [Casimir Effect](physics/casimir_effect.py)
807+
* [Center Of Mass](physics/center_of_mass.py)
813808
* [Centripetal Force](physics/centripetal_force.py)
814809
* [Coulombs Law](physics/coulombs_law.py)
810+
* [Doppler Frequency](physics/doppler_frequency.py)
815811
* [Grahams Law](physics/grahams_law.py)
816812
* [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py)
817813
* [Hubble Parameter](physics/hubble_parameter.py)

backtracking/n_queens.py

Lines changed: 26 additions & 27 deletions
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))

boolean_algebra/nor_gate.py

Lines changed: 37 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
"""
2-
A NOR Gate is a logic gate in boolean algebra which results to false(0)
3-
if any of the input is 1, and True(1) if both the inputs are 0.
2+
A NOR Gate is a logic gate in boolean algebra which results in false(0) if any of the
3+
inputs is 1, and True(1) if all inputs are 0.
44
Following is the truth table of a NOR Gate:
5-
| Input 1 | Input 2 | Output |
6-
| 0 | 0 | 1 |
7-
| 0 | 1 | 0 |
8-
| 1 | 0 | 0 |
9-
| 1 | 1 | 0 |
5+
Truth Table of NOR Gate:
6+
| Input 1 | Input 2 | Output |
7+
| 0 | 0 | 1 |
8+
| 0 | 1 | 0 |
9+
| 1 | 0 | 0 |
10+
| 1 | 1 | 0 |
1011
11-
Following is the code implementation of the NOR Gate
12+
Code provided by Akshaj Vishwanathan
13+
https://www.geeksforgeeks.org/logic-gates-in-python
1214
"""
15+
from collections.abc import Callable
1316

1417

1518
def nor_gate(input_1: int, input_2: int) -> int:
@@ -30,19 +33,35 @@ def nor_gate(input_1: int, input_2: int) -> int:
3033
return int(input_1 == input_2 == 0)
3134

3235

33-
def main() -> None:
34-
print("Truth Table of NOR Gate:")
35-
print("| Input 1 | Input 2 | Output |")
36-
print(f"| 0 | 0 | {nor_gate(0, 0)} |")
37-
print(f"| 0 | 1 | {nor_gate(0, 1)} |")
38-
print(f"| 1 | 0 | {nor_gate(1, 0)} |")
39-
print(f"| 1 | 1 | {nor_gate(1, 1)} |")
36+
def truth_table(func: Callable) -> str:
37+
"""
38+
>>> print(truth_table(nor_gate))
39+
Truth Table of NOR Gate:
40+
| Input 1 | Input 2 | Output |
41+
| 0 | 0 | 1 |
42+
| 0 | 1 | 0 |
43+
| 1 | 0 | 0 |
44+
| 1 | 1 | 0 |
45+
"""
46+
47+
def make_table_row(items: list | tuple) -> str:
48+
"""
49+
>>> make_table_row(("One", "Two", "Three"))
50+
'| One | Two | Three |'
51+
"""
52+
return f"| {' | '.join(f'{item:^8}' for item in items)} |"
53+
54+
return "\n".join(
55+
(
56+
"Truth Table of NOR Gate:",
57+
make_table_row(("Input 1", "Input 2", "Output")),
58+
*[make_table_row((i, j, func(i, j))) for i in (0, 1) for j in (0, 1)],
59+
)
60+
)
4061

4162

4263
if __name__ == "__main__":
4364
import doctest
4465

4566
doctest.testmod()
46-
main()
47-
"""Code provided by Akshaj Vishwanathan"""
48-
"""Reference: https://www.geeksforgeeks.org/logic-gates-in-python/"""
67+
print(truth_table(nor_gate))

ciphers/onepad_cipher.py

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,27 @@
44
class Onepad:
55
@staticmethod
66
def encrypt(text: str) -> tuple[list[int], list[int]]:
7-
"""Function to encrypt text using pseudo-random numbers"""
7+
"""
8+
Function to encrypt text using pseudo-random numbers
9+
>>> Onepad().encrypt("")
10+
([], [])
11+
>>> Onepad().encrypt([])
12+
([], [])
13+
>>> random.seed(1)
14+
>>> Onepad().encrypt(" ")
15+
([6969], [69])
16+
>>> random.seed(1)
17+
>>> Onepad().encrypt("Hello")
18+
([9729, 114756, 4653, 31309, 10492], [69, 292, 33, 131, 61])
19+
>>> Onepad().encrypt(1)
20+
Traceback (most recent call last):
21+
...
22+
TypeError: 'int' object is not iterable
23+
>>> Onepad().encrypt(1.1)
24+
Traceback (most recent call last):
25+
...
26+
TypeError: 'float' object is not iterable
27+
"""
828
plain = [ord(i) for i in text]
929
key = []
1030
cipher = []
@@ -17,7 +37,20 @@ def encrypt(text: str) -> tuple[list[int], list[int]]:
1737

1838
@staticmethod
1939
def decrypt(cipher: list[int], key: list[int]) -> str:
20-
"""Function to decrypt text using pseudo-random numbers."""
40+
"""
41+
Function to decrypt text using pseudo-random numbers.
42+
>>> Onepad().decrypt([], [])
43+
''
44+
>>> Onepad().decrypt([35], [])
45+
''
46+
>>> Onepad().decrypt([], [35])
47+
Traceback (most recent call last):
48+
...
49+
IndexError: list index out of range
50+
>>> random.seed(1)
51+
>>> Onepad().decrypt([9729, 114756, 4653, 31309, 10492], [69, 292, 33, 131, 61])
52+
'Hello'
53+
"""
2154
plain = []
2255
for i in range(len(key)):
2356
p = int((cipher[i] - (key[i]) ** 2) / key[i])

0 commit comments

Comments
 (0)