Skip to content

Commit 3c0e23c

Browse files
Merge branch 'master' into improve-maths-check-polygon
2 parents 5787ac4 + 78d3358 commit 3c0e23c

44 files changed

Lines changed: 4353 additions & 249 deletions

Some content is hidden

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

‎DIRECTORY.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
* [Generate Parentheses Iterative](backtracking/generate_parentheses_iterative.py)
6363
* [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py)
6464
* [Knight Tour](backtracking/knight_tour.py)
65+
* [M Coloring Problem](backtracking/m_coloring_problem.py)
6566
* [Match Word Pattern](backtracking/match_word_pattern.py)
6667
* [Minimax](backtracking/minimax.py)
6768
* [N Queens](backtracking/n_queens.py)
@@ -108,6 +109,11 @@
108109

109110
## [Blockchain](blockchain)
110111
* [Diophantine Equation](blockchain/diophantine_equation.py)
112+
* [Merkle Tree](blockchain/merkle_tree.py)
113+
* [Proof Of Stake](blockchain/proof_of_stake.py)
114+
* [Proof Of Work](blockchain/proof_of_work.py)
115+
* [Simple Blockchain](blockchain/simple_blockchain.py)
116+
* [Simple Proof Of Work](blockchain/simple_proof_of_work.py)
111117

112118
## [Boolean Algebra](boolean_algebra)
113119
* [And Gate](boolean_algebra/and_gate.py)
@@ -166,6 +172,7 @@
166172
* [Porta Cipher](ciphers/porta_cipher.py)
167173
* [Rabin Miller](ciphers/rabin_miller.py)
168174
* [Rail Fence Cipher](ciphers/rail_fence_cipher.py)
175+
* [Rc4](ciphers/rc4.py)
169176
* [Rot13](ciphers/rot13.py)
170177
* [Rsa Cipher](ciphers/rsa_cipher.py)
171178
* [Rsa Factorization](ciphers/rsa_factorization.py)
@@ -180,6 +187,7 @@
180187
* [Vernam Cipher](ciphers/vernam_cipher.py)
181188
* [Vigenere Cipher](ciphers/vigenere_cipher.py)
182189
* [Xor Cipher](ciphers/xor_cipher.py)
190+
* [Xtea](ciphers/xtea.py)
183191

184192
## [Computer Vision](computer_vision)
185193
* [Cnn Classification](computer_vision/cnn_classification.py)
@@ -198,20 +206,26 @@
198206
## [Conversions](conversions)
199207
* [Astronomical Length Scale Conversion](conversions/astronomical_length_scale_conversion.py)
200208
* [Binary To Decimal](conversions/binary_to_decimal.py)
209+
* [Binary To Excess3](conversions/binary_to_excess3.py)
210+
* [Binary To Gray](conversions/binary_to_gray.py)
211+
* [Binary To Gray Code](conversions/binary_to_gray_code.py)
201212
* [Binary To Hexadecimal](conversions/binary_to_hexadecimal.py)
202213
* [Binary To Octal](conversions/binary_to_octal.py)
203214
* [Convert Number To Words](conversions/convert_number_to_words.py)
204215
* [Decimal To Any](conversions/decimal_to_any.py)
205216
* [Decimal To Binary](conversions/decimal_to_binary.py)
206217
* [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py)
207218
* [Decimal To Octal](conversions/decimal_to_octal.py)
219+
* [Endianness](conversions/endianness.py)
208220
* [Energy Conversions](conversions/energy_conversions.py)
209221
* [Excel Title To Column](conversions/excel_title_to_column.py)
210222
* [Hex To Bin](conversions/hex_to_bin.py)
211223
* [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py)
224+
* [Int To Negative Binary Base](conversions/int_to_negative_binary_base.py)
212225
* [Ipv4 Conversion](conversions/ipv4_conversion.py)
213226
* [Length Conversion](conversions/length_conversion.py)
214227
* [Molecular Chemistry](conversions/molecular_chemistry.py)
228+
* [Negative Binary Base To Int](conversions/negative_binary_base_to_int.py)
215229
* [Octal To Binary](conversions/octal_to_binary.py)
216230
* [Octal To Decimal](conversions/octal_to_decimal.py)
217231
* [Octal To Hexadecimal](conversions/octal_to_hexadecimal.py)
@@ -540,6 +554,7 @@
540554
## [Geodesy](geodesy)
541555
* [Haversine Distance](geodesy/haversine_distance.py)
542556
* [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py)
557+
* [Radar Target Calculation](geodesy/radar_target_calculation.py)
543558

544559
## [Geometry](geometry)
545560
* [Geometry](geometry/geometry.py)
@@ -625,6 +640,7 @@
625640
* [Strongly Connected Components](graphs/strongly_connected_components.py)
626641
* [Tarjans Scc](graphs/tarjans_scc.py)
627642
* Tests
643+
* [Test Graphs Floyd Warshall](graphs/tests/test_graphs_floyd_warshall.py)
628644
* [Test Johnson](graphs/tests/test_johnson.py)
629645
* [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py)
630646
* [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py)
@@ -689,6 +705,7 @@
689705
* [Astar](machine_learning/astar.py)
690706
* [Automatic Differentiation](machine_learning/automatic_differentiation.py)
691707
* [Data Transformations](machine_learning/data_transformations.py)
708+
* [Dbscan](machine_learning/dbscan.py)
692709
* [Decision Tree](machine_learning/decision_tree.py)
693710
* [Dimensionality Reduction](machine_learning/dimensionality_reduction.py)
694711
* [Federated Averaging](machine_learning/federated_averaging.py)
@@ -712,14 +729,19 @@
712729
* [Loss Functions](machine_learning/loss_functions.py)
713730
* Lstm
714731
* [Lstm Prediction](machine_learning/lstm/lstm_prediction.py)
732+
* [Mab](machine_learning/mab.py)
733+
* [Mean Shift](machine_learning/mean_shift.py)
715734
* [Mfcc](machine_learning/mfcc.py)
716735
* [Mini Batch Gradient Descent](machine_learning/mini_batch_gradient_descent.py)
717736
* [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py)
737+
* [Naive Bayes Text Classification](machine_learning/naive_bayes_text_classification.py)
738+
* [Ordinary Least Squares Regression](machine_learning/ordinary_least_squares_regression.py)
718739
* [Polynomial Regression](machine_learning/polynomial_regression.py)
719740
* [Principle Component Analysis](machine_learning/principle_component_analysis.py)
720741
* [Q Learning](machine_learning/q_learning.py)
721742
* [Random Forest Classifier](machine_learning/random_forest_classifier.py)
722743
* [Random Forest Regressor](machine_learning/random_forest_regressor.py)
744+
* [Rmsprop](machine_learning/rmsprop.py)
723745
* [Scoring Functions](machine_learning/scoring_functions.py)
724746
* [Self Organizing Map](machine_learning/self_organizing_map.py)
725747
* [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py)
@@ -736,6 +758,7 @@
736758
* [Arc Length](maths/arc_length.py)
737759
* [Area](maths/area.py)
738760
* [Area Under Curve](maths/area_under_curve.py)
761+
* [Autocorrelation](maths/autocorrelation.py)
739762
* [Average Absolute Deviation](maths/average_absolute_deviation.py)
740763
* [Average Mean](maths/average_mean.py)
741764
* [Average Median](maths/average_median.py)
@@ -781,6 +804,7 @@
781804
* [Fibonacci](maths/fibonacci.py)
782805
* [Find Max](maths/find_max.py)
783806
* [Find Min](maths/find_min.py)
807+
* [First Fundamental Form](maths/first_fundamental_form.py)
784808
* [Floor](maths/floor.py)
785809
* [Gamma](maths/gamma.py)
786810
* [Gaussian](maths/gaussian.py)
@@ -843,6 +867,7 @@
843867
* [Square Root](maths/numerical_analysis/square_root.py)
844868
* [Weierstrass Method](maths/numerical_analysis/weierstrass_method.py)
845869
* [Odd Sieve](maths/odd_sieve.py)
870+
* [Padovan Sequence](maths/padovan_sequence.py)
846871
* [Pell Number](maths/pell_number.py)
847872
* [Perfect Cube](maths/perfect_cube.py)
848873
* [Perfect Number](maths/perfect_number.py)
@@ -872,6 +897,8 @@
872897
* [Reverse Factorial Recursive](maths/reverse_factorial_recursive.py)
873898
* [Segmented Sieve](maths/segmented_sieve.py)
874899
* Series
900+
* [Alternate Harmonic Series](maths/series/alternate_harmonic_series.py)
901+
* [Alternating Harmonic Series](maths/series/alternating_harmonic_series.py)
875902
* [Arithmetic](maths/series/arithmetic.py)
876903
* [Geometric](maths/series/geometric.py)
877904
* [Geometric Series](maths/series/geometric_series.py)
@@ -911,6 +938,7 @@
911938
* [Polygonal Numbers](maths/special_numbers/polygonal_numbers.py)
912939
* [Pronic Number](maths/special_numbers/pronic_number.py)
913940
* [Proth Number](maths/special_numbers/proth_number.py)
941+
* [Spy Number](maths/special_numbers/spy_number.py)
914942
* [Triangular Numbers](maths/special_numbers/triangular_numbers.py)
915943
* [Trimorphic Number](maths/special_numbers/trimorphic_number.py)
916944
* [Ugly Numbers](maths/special_numbers/ugly_numbers.py)
@@ -945,6 +973,7 @@
945973
* [Count Paths](matrix/count_paths.py)
946974
* [Cramers Rule 2X2](matrix/cramers_rule_2x2.py)
947975
* [Inverse Of Matrix](matrix/inverse_of_matrix.py)
976+
* [Kronecker Product](matrix/kronecker_product.py)
948977
* [Largest Square Area In Matrix](matrix/largest_square_area_in_matrix.py)
949978
* [Matrix Based Game](matrix/matrix_based_game.py)
950979
* [Matrix Class](matrix/matrix_class.py)
@@ -1028,6 +1057,7 @@
10281057
* [Altitude Pressure](physics/altitude_pressure.py)
10291058
* [Archimedes Principle Of Buoyant Force](physics/archimedes_principle_of_buoyant_force.py)
10301059
* [Basic Orbital Capture](physics/basic_orbital_capture.py)
1060+
* [Boyles Law](physics/boyles_law.py)
10311061
* [Bragg Angle](physics/bragg_angle.py)
10321062
* [Casimir Effect](physics/casimir_effect.py)
10331063
* [Center Of Mass](physics/center_of_mass.py)
@@ -1384,6 +1414,7 @@
13841414

13851415
## [Quantum](quantum)
13861416
* [Q Fourier Transform](quantum/q_fourier_transform.py)
1417+
* [Shor Algorithm](quantum/shor_algorithm.py)
13871418

13881419
## [Scheduling](scheduling)
13891420
* [Cpuschedulingalgorithms](scheduling/cpuschedulingalgorithms.py)
@@ -1483,6 +1514,7 @@
14831514
* [Autocomplete Using Trie](strings/autocomplete_using_trie.py)
14841515
* [Barcode Validator](strings/barcode_validator.py)
14851516
* [Bitap String Match](strings/bitap_string_match.py)
1517+
* [Booths Algorithm](strings/booths_algorithm.py)
14861518
* [Boyer Moore Horspool](strings/boyer_moore_horspool.py)
14871519
* [Boyer Moore Search](strings/boyer_moore_search.py)
14881520
* [Camel Case To Snake Case](strings/camel_case_to_snake_case.py)
@@ -1509,6 +1541,7 @@
15091541
* [Jaro Winkler](strings/jaro_winkler.py)
15101542
* [Join](strings/join.py)
15111543
* [Knuth Morris Pratt](strings/knuth_morris_pratt.py)
1544+
* [Largest Smallest Words](strings/largest_smallest_words.py)
15121545
* [Levenshtein Distance](strings/levenshtein_distance.py)
15131546
* [Lower](strings/lower.py)
15141547
* [Manacher](strings/manacher.py)
@@ -1545,6 +1578,8 @@
15451578
* [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py)
15461579
* [Crawl Google Results](web_programming/crawl_google_results.py)
15471580
* [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py)
1581+
* [Crypto Price](web_programming/crypto_price.py)
1582+
* [Crypto Price Tracker](web_programming/crypto_price_tracker.py)
15481583
* [Currency Converter](web_programming/currency_converter.py)
15491584
* [Current Stock Price](web_programming/current_stock_price.py)
15501585
* [Current Weather](web_programming/current_weather.py)

‎backtracking/m_coloring_problem.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
def is_safe(
2+
node: int,
3+
color: int,
4+
graph: list[list[int]],
5+
num_vertices: int,
6+
col: list[int],
7+
) -> bool:
8+
"""
9+
Check if it is safe to assign a color to a node.
10+
11+
>>> is_safe(0, 1, [[0,1],[1,0]], 2, [0,1])
12+
False
13+
>>> is_safe(0, 2, [[0,1],[1,0]], 2, [0,1])
14+
True
15+
"""
16+
return all(
17+
not (graph[node][k] == 1 and col[k] == color) for k in range(num_vertices)
18+
)
19+
20+
21+
def solve(
22+
node: int,
23+
col: list[int],
24+
max_colors: int,
25+
num_vertices: int,
26+
graph: list[list[int]],
27+
) -> bool:
28+
"""
29+
Recursively try to color the graph using at most max_colors.
30+
31+
>>> solve(0, [0]*3, 3, 3, [[0,1,0],[1,0,1],[0,1,0]])
32+
True
33+
>>> solve(0, [0]*3, 2, 3, [[0,1,0],[1,0,1],[0,1,0]])
34+
True
35+
"""
36+
if node == num_vertices:
37+
return True
38+
for c in range(1, max_colors + 1):
39+
if is_safe(node, c, graph, num_vertices, col):
40+
col[node] = c
41+
if solve(node + 1, col, max_colors, num_vertices, graph):
42+
return True
43+
col[node] = 0
44+
return False
45+
46+
47+
def graph_coloring(graph: list[list[int]], max_colors: int, num_vertices: int) -> bool:
48+
"""
49+
Determine if the graph can be colored with at most max_colors.
50+
51+
>>> graph_coloring([[0,1,1],[1,0,1],[1,1,0]], 3, 3)
52+
True
53+
>>> graph_coloring([[0,1,1],[1,0,1],[1,1,0]], 2, 3)
54+
False
55+
"""
56+
col = [0] * num_vertices
57+
return solve(0, col, max_colors, num_vertices, graph)
58+
59+
60+
if __name__ == "__main__":
61+
import doctest
62+
63+
doctest.testmod()
64+
65+
num_vertices = int(input("Enter vertices: "))
66+
num_edges = int(input("Enter edges: "))
67+
graph = [[0] * num_vertices for _ in range(num_vertices)]
68+
69+
print("Enter edges (u v):")
70+
for _ in range(num_edges):
71+
try:
72+
u, v = map(int, input().split())
73+
if 0 <= u < num_vertices and 0 <= v < num_vertices:
74+
graph[u][v] = 1
75+
graph[v][u] = 1
76+
else:
77+
print("Invalid edge.")
78+
except ValueError:
79+
print("Invalid input.")
80+
81+
max_colors = int(input("Enter max colors: "))
82+
83+
if graph_coloring(graph, max_colors, num_vertices):
84+
print("Coloring possible.")
85+
else:
86+
print("Coloring not possible.")

‎blockchain/merkle_tree.py‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
"""
2+
Merkle Tree Construction and Verification
3+
4+
This module implements the construction of a Merkle Tree and
5+
verification of inclusion proofs for blockchain data integrity.
6+
7+
Each leaf is a SHA-256 hash of a transaction, and internal nodes are
8+
computed by hashing the concatenation of their child nodes.
9+
10+
References:
11+
https://en.wikipedia.org/wiki/Merkle_tree
12+
"""
13+
14+
import hashlib
15+
16+
17+
def sha256(data: str) -> str:
18+
"""
19+
Compute the SHA-256 hash of the given string.
20+
21+
Args:
22+
data (str): Input string.
23+
24+
Returns:
25+
str: Hexadecimal SHA-256 hash of the input.
26+
27+
Example:
28+
>>> sha256("abc")
29+
'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'
30+
"""
31+
return hashlib.sha256(data.encode()).hexdigest()
32+
33+
34+
def build_merkle_tree(leaves: list[str]) -> list[list[str]]:
35+
"""
36+
Build a Merkle Tree from the given leaf nodes.
37+
38+
Args:
39+
leaves: List of data strings (transactions).
40+
41+
Returns:
42+
A list of lists representing tree levels,
43+
with the last level containing the Merkle root.
44+
45+
>>> len(build_merkle_tree(["a", "b", "c", "d"])[-1][0])
46+
64
47+
"""
48+
if not leaves:
49+
raise ValueError("Leaf list cannot be empty.")
50+
51+
current_level = [sha256(x) for x in leaves]
52+
tree = [current_level]
53+
54+
while len(current_level) > 1:
55+
next_level = []
56+
for i in range(0, len(current_level), 2):
57+
left = current_level[i]
58+
right = current_level[i + 1] if i + 1 < len(current_level) else left
59+
next_level.append(sha256(left + right))
60+
current_level = next_level
61+
tree.append(current_level)
62+
63+
return tree
64+
65+
66+
def merkle_root(leaves: list[str]) -> str:
67+
"""
68+
Return the Merkle root hash for a given list of data.
69+
70+
>>> r = merkle_root(["tx1", "tx2", "tx3"])
71+
>>> isinstance(r, str)
72+
True
73+
"""
74+
return build_merkle_tree(leaves)[-1][0]
75+
76+
77+
def verify_proof(leaf: str, proof: list[str], root: str) -> bool:
78+
"""
79+
Verify inclusion of a leaf using a Merkle proof.
80+
81+
Args:
82+
leaf: Original data string.
83+
proof: List of sibling hashes up the path.
84+
root: Expected Merkle root hash.
85+
86+
Returns:
87+
True if proof is valid, else False.
88+
89+
>>> data = ["a", "b", "c", "d"]
90+
>>> tree = build_merkle_tree(data)
91+
>>> root = tree[-1][0]
92+
>>> leaf = "a"
93+
>>> proof = [sha256("b"), sha256(sha256("c") + sha256("d"))]
94+
>>> verify_proof(leaf, proof, root)
95+
True
96+
"""
97+
computed_hash = sha256(leaf)
98+
for sibling in proof:
99+
combined = sha256(computed_hash + sibling)
100+
computed_hash = combined
101+
return computed_hash == root
102+
103+
104+
if __name__ == "__main__":
105+
import doctest
106+
107+
doctest.testmod()

0 commit comments

Comments
 (0)