Skip to content

Commit 67e1d5e

Browse files
authored
Merge branch 'master' into master
2 parents a458148 + 00d9ebb commit 67e1d5e

18 files changed

Lines changed: 2893 additions & 198 deletions

DIRECTORY.md

Lines changed: 14 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,9 @@
108109

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

112116
## [Boolean Algebra](boolean_algebra)
113117
* [And Gate](boolean_algebra/and_gate.py)
@@ -166,6 +170,7 @@
166170
* [Porta Cipher](ciphers/porta_cipher.py)
167171
* [Rabin Miller](ciphers/rabin_miller.py)
168172
* [Rail Fence Cipher](ciphers/rail_fence_cipher.py)
173+
* [Rc4](ciphers/rc4.py)
169174
* [Rot13](ciphers/rot13.py)
170175
* [Rsa Cipher](ciphers/rsa_cipher.py)
171176
* [Rsa Factorization](ciphers/rsa_factorization.py)
@@ -180,6 +185,7 @@
180185
* [Vernam Cipher](ciphers/vernam_cipher.py)
181186
* [Vigenere Cipher](ciphers/vigenere_cipher.py)
182187
* [Xor Cipher](ciphers/xor_cipher.py)
188+
* [Xtea](ciphers/xtea.py)
183189

184190
## [Computer Vision](computer_vision)
185191
* [Cnn Classification](computer_vision/cnn_classification.py)
@@ -198,13 +204,17 @@
198204
## [Conversions](conversions)
199205
* [Astronomical Length Scale Conversion](conversions/astronomical_length_scale_conversion.py)
200206
* [Binary To Decimal](conversions/binary_to_decimal.py)
207+
* [Binary To Excess3](conversions/binary_to_excess3.py)
208+
* [Binary To Gray](conversions/binary_to_gray.py)
209+
* [Binary To Gray Code](conversions/binary_to_gray_code.py)
201210
* [Binary To Hexadecimal](conversions/binary_to_hexadecimal.py)
202211
* [Binary To Octal](conversions/binary_to_octal.py)
203212
* [Convert Number To Words](conversions/convert_number_to_words.py)
204213
* [Decimal To Any](conversions/decimal_to_any.py)
205214
* [Decimal To Binary](conversions/decimal_to_binary.py)
206215
* [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py)
207216
* [Decimal To Octal](conversions/decimal_to_octal.py)
217+
* [Endianness](conversions/endianness.py)
208218
* [Energy Conversions](conversions/energy_conversions.py)
209219
* [Excel Title To Column](conversions/excel_title_to_column.py)
210220
* [Hex To Bin](conversions/hex_to_bin.py)
@@ -540,6 +550,7 @@
540550
## [Geodesy](geodesy)
541551
* [Haversine Distance](geodesy/haversine_distance.py)
542552
* [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py)
553+
* [Radar Target Calculation](geodesy/radar_target_calculation.py)
543554

544555
## [Geometry](geometry)
545556
* [Geometry](geometry/geometry.py)
@@ -689,6 +700,7 @@
689700
* [Astar](machine_learning/astar.py)
690701
* [Automatic Differentiation](machine_learning/automatic_differentiation.py)
691702
* [Data Transformations](machine_learning/data_transformations.py)
703+
* [Dbscan](machine_learning/dbscan.py)
692704
* [Decision Tree](machine_learning/decision_tree.py)
693705
* [Dimensionality Reduction](machine_learning/dimensionality_reduction.py)
694706
* [Federated Averaging](machine_learning/federated_averaging.py)
@@ -712,11 +724,13 @@
712724
* [Loss Functions](machine_learning/loss_functions.py)
713725
* Lstm
714726
* [Lstm Prediction](machine_learning/lstm/lstm_prediction.py)
727+
* [Mab](machine_learning/mab.py)
715728
* [Mean Shift](machine_learning/mean_shift.py)
716729
* [Mfcc](machine_learning/mfcc.py)
717730
* [Mini Batch Gradient Descent](machine_learning/mini_batch_gradient_descent.py)
718731
* [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py)
719732
* [Naive Bayes Text Classification](machine_learning/naive_bayes_text_classification.py)
733+
* [Ordinary Least Squares Regression](machine_learning/ordinary_least_squares_regression.py)
720734
* [Polynomial Regression](machine_learning/polynomial_regression.py)
721735
* [Principle Component Analysis](machine_learning/principle_component_analysis.py)
722736
* [Q Learning](machine_learning/q_learning.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)