Skip to content

Commit 327e9fa

Browse files
authored
Merge branch 'TheAlgorithms:master' into master
2 parents 35de5a6 + 544f48f commit 327e9fa

18 files changed

Lines changed: 526 additions & 47 deletions

File tree

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ repos:
1616
- id: auto-walrus
1717

1818
- repo: https://github.com/astral-sh/ruff-pre-commit
19-
rev: v0.12.10
19+
rev: v0.12.11
2020
hooks:
2121
- id: ruff-check
2222
- id: ruff-format

DIRECTORY.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
* [Combination Sum](backtracking/combination_sum.py)
1313
* [Crossword Puzzle Solver](backtracking/crossword_puzzle_solver.py)
1414
* [Generate Parentheses](backtracking/generate_parentheses.py)
15+
* [Generate Parentheses Iterative](backtracking/generate_parentheses_iterative.py)
1516
* [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py)
1617
* [Knight Tour](backtracking/knight_tour.py)
1718
* [Match Word Pattern](backtracking/match_word_pattern.py)
@@ -174,6 +175,7 @@
174175

175176
## Data Compression
176177
* [Burrows Wheeler](data_compression/burrows_wheeler.py)
178+
* [Coordinate Compression](data_compression/coordinate_compression.py)
177179
* [Huffman](data_compression/huffman.py)
178180
* [Lempel Ziv](data_compression/lempel_ziv.py)
179181
* [Lempel Ziv Decompress](data_compression/lempel_ziv_decompress.py)
@@ -723,6 +725,7 @@
723725
* [Secant Method](maths/numerical_analysis/secant_method.py)
724726
* [Simpson Rule](maths/numerical_analysis/simpson_rule.py)
725727
* [Square Root](maths/numerical_analysis/square_root.py)
728+
* [Weierstrass Method](maths/numerical_analysis/weierstrass_method.py)
726729
* [Odd Sieve](maths/odd_sieve.py)
727730
* [Perfect Cube](maths/perfect_cube.py)
728731
* [Perfect Number](maths/perfect_number.py)
@@ -1298,6 +1301,7 @@
12981301
* [Shell Sort](sorts/shell_sort.py)
12991302
* [Shrink Shell Sort](sorts/shrink_shell_sort.py)
13001303
* [Slowsort](sorts/slowsort.py)
1304+
* [Stalin Sort](sorts/stalin_sort.py)
13011305
* [Stooge Sort](sorts/stooge_sort.py)
13021306
* [Strand Sort](sorts/strand_sort.py)
13031307
* [Tim Sort](sorts/tim_sort.py)

README.md

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
<img src="https://raw.githubusercontent.com/TheAlgorithms/website/1cd824df116b27029f17c2d1b42d81731f28a920/public/logo.svg" height="100">
55
</a>
66
<h1><a href="https://github.com/TheAlgorithms/">The Algorithms</a> - Python</h1>
7+
78
<!-- Labels: -->
89
<!-- First row: -->
910
<a href="https://gitpod.io/#https://github.com/TheAlgorithms/Python">
@@ -19,6 +20,7 @@
1920
<a href="https://gitter.im/TheAlgorithms/community">
2021
<img src="https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square" height="20" alt="Gitter chat">
2122
</a>
23+
2224
<!-- Second row: -->
2325
<br>
2426
<a href="https://github.com/TheAlgorithms/Python/actions">
@@ -30,20 +32,21 @@
3032
<a href="https://docs.astral.sh/ruff/formatter/">
3133
<img src="https://img.shields.io/static/v1?label=code%20style&message=ruff&color=black&style=flat-square" height="20" alt="code style: black">
3234
</a>
35+
3336
<!-- Short description: -->
34-
<h3>All algorithms implemented in Python - for education</h3>
37+
<h3>All algorithms implemented in Python - for education 📚</h3>
3538
</div>
3639

3740
Implementations are for learning purposes only. They may be less efficient than the implementations in the Python standard library. Use them at your discretion.
3841

39-
## Getting Started
42+
## 🚀 Getting Started
4043

41-
Read through our [Contribution Guidelines](CONTRIBUTING.md) before you contribute.
44+
📋 Read through our [Contribution Guidelines](CONTRIBUTING.md) before you contribute.
4245

43-
## Community Channels
46+
## 🌐 Community Channels
4447

4548
We are on [Discord](https://the-algorithms.com/discord) and [Gitter](https://gitter.im/TheAlgorithms/community)! Community channels are a great way for you to ask questions and get help. Please join us!
4649

47-
## List of Algorithms
50+
## 📜 List of Algorithms
4851

4952
See our [directory](DIRECTORY.md) for easier navigation and a better overview of the project.

backtracking/combination_sum.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,18 @@ def combination_sum(candidates: list, target: int) -> list:
4747
>>> combination_sum([-8, 2.3, 0], 1)
4848
Traceback (most recent call last):
4949
...
50-
RecursionError: maximum recursion depth exceeded
50+
ValueError: All elements in candidates must be non-negative
51+
>>> combination_sum([], 1)
52+
Traceback (most recent call last):
53+
...
54+
ValueError: Candidates list should not be empty
5155
"""
56+
if not candidates:
57+
raise ValueError("Candidates list should not be empty")
58+
59+
if any(x < 0 for x in candidates):
60+
raise ValueError("All elements in candidates must be non-negative")
61+
5262
path = [] # type: list[int]
5363
answer = [] # type: list[int]
5464
backtrack(candidates, path, answer, target, 0)
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
def generate_parentheses_iterative(length: int) -> list:
2+
"""
3+
Generate all valid combinations of parentheses (Iterative Approach).
4+
5+
The algorithm works as follows:
6+
1. Initialize an empty list to store the combinations.
7+
2. Initialize a stack to keep track of partial combinations.
8+
3. Start with empty string and push it onstack along with the counts of '(' and ')'.
9+
4. While the stack is not empty:
10+
a. Pop a partial combination and its open and close counts from the stack.
11+
b. If the combination length is equal to 2*length, add it to the result.
12+
c. If open count < length, push new combination with added '(' on stack.
13+
d. If close count < open count, push new combination with added ')' on stack.
14+
5. Return the result containing all valid combinations.
15+
16+
Args:
17+
length: The desired length of the parentheses combinations
18+
19+
Returns:
20+
A list of strings representing valid combinations of parentheses
21+
22+
Time Complexity:
23+
O(2^(2*length))
24+
25+
Space Complexity:
26+
O(2^(2*length))
27+
28+
>>> generate_parentheses_iterative(3)
29+
['()()()', '()(())', '(())()', '(()())', '((()))']
30+
>>> generate_parentheses_iterative(2)
31+
['()()', '(())']
32+
>>> generate_parentheses_iterative(1)
33+
['()']
34+
>>> generate_parentheses_iterative(0)
35+
['']
36+
"""
37+
result = []
38+
stack = []
39+
40+
# Each element in stack is a tuple (current_combination, open_count, close_count)
41+
stack.append(("", 0, 0))
42+
43+
while stack:
44+
current_combination, open_count, close_count = stack.pop()
45+
46+
if len(current_combination) == 2 * length:
47+
result.append(current_combination)
48+
49+
if open_count < length:
50+
stack.append((current_combination + "(", open_count + 1, close_count))
51+
52+
if close_count < open_count:
53+
stack.append((current_combination + ")", open_count, close_count + 1))
54+
55+
return result
56+
57+
58+
if __name__ == "__main__":
59+
import doctest
60+
61+
doctest.testmod()
62+
print(generate_parentheses_iterative(3))

blockchain/README.md

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,44 @@
11
# Blockchain
22

3-
A Blockchain is a type of **distributed ledger** technology (DLT) that consists of growing list of records, called **blocks**, that are securely linked together using **cryptography**.
3+
A Blockchain is a type of **distributed ledger** technology (DLT) that consists of a growing list of records, called **blocks**, that are securely linked together using **cryptography**.
44

5-
Let's breakdown the terminologies in the above definition. We find below terminologies,
5+
Let's break down the terminologies in the above definition. We find below terminologies,
66

77
- Digital Ledger Technology (DLT)
88
- Blocks
99
- Cryptography
1010

1111
## Digital Ledger Technology
1212

13-
It is otherwise called as distributed ledger technology. It is simply the opposite of centralized database. Firstly, what is a **ledger**? A ledger is a book or collection of accounts that records account transactions.
13+
Blockchain is also called distributed ledger technology. It is simply the opposite of a centralized database. Firstly, what is a **ledger**? A ledger is a book or collection of accounts that records account transactions.
1414

15-
*Why is Blockchain addressed as digital ledger if it can record more than account transactions? What other transaction details and information can it hold?*
15+
*Why is Blockchain addressed as a digital ledger if it can record more than account transactions? What other transaction details and information can it hold?*
1616

17-
Digital Ledger Technology is just a ledger which is shared among multiple nodes. This way there exist no need for central authority to hold the info. Okay, how is it differentiated from central database and what are their benefits?
17+
Digital Ledger Technology is just a ledger that is shared among multiple nodes. This way there exists no need for a central authority to hold the info. Okay, how is it differentiated from a central database and what are their benefits?
1818

19-
There is an organization which has 4 branches whose data are stored in a centralized database. So even if one branch needs any data from ledger they need an approval from database in charge. And if one hacks the central database he gets to tamper and control all the data.
19+
Suppose that there is an organization that has 4 branches whose data are stored in a centralized database. So even if one branch needs any data from the ledger it needs approval from the database in charge. And if one hacks the central database he gets to tamper and control all the data.
2020

21-
Now lets assume every branch has a copy of the ledger and then once anything is added to the ledger by anyone branch it is gonna automatically reflect in all other ledgers available in other branch. This is done using Peer-to-peer network.
21+
Now let's assume every branch has a copy of the ledger and then once anything is added to the ledger by any branch it is gonna automatically reflect in all other ledgers available in other branches. This is done using a peer-to-peer network.
2222

23-
So this means even if information is tampered in one branch we can find out. If one branch is hacked we can be alerted ,so we can safeguard other branches. Now, assume these branches as computers or nodes and the ledger is a transaction record or digital receipt. If one ledger is hacked in a node we can detect since there will be a mismatch in comparison with other node information. So this is the concept of Digital Ledger Technology.
23+
This means that even if information is tampered with in one branch we can find out. If one branch is hacked we can be alerted, so we can safeguard other branches. Now, assume these branches as computers or nodes and the ledger is a transaction record or digital receipt. If one ledger is hacked in a node we can detect since there will be a mismatch in comparison with other node information. So this is the concept of Digital Ledger Technology.
2424

2525
*Is it required for all nodes to have access to all information in other nodes? Wouldn't this require enormous storage space in each node?*
2626

2727
## Blocks
2828

29-
In short a block is nothing but collections of records with a labelled header. These are connected cryptographically. Once a new block is added to a chain, the previous block is connected, more precisely said as locked and hence, will remain unaltered. We can understand this concept once we get a clear understanding of working mechanism of blockchain.
29+
In short, a block is nothing but a collection of records with a labelled header. These are connected cryptographically. Once a new block is added to a chain, the previous block is connected, more precisely said as locked, and hence will remain unaltered. We can understand this concept once we get a clear understanding of the working mechanism of blockchain.
3030

3131
## Cryptography
3232

33-
It is the practice and study of secure communication techniques in the midst of adversarial behavior. More broadly, cryptography is the creation and analysis of protocols that prevent third parties or the general public from accessing private messages.
33+
Cryptography is the practice and study of secure communication techniques amid adversarial behavior. More broadly, cryptography is the creation and analysis of protocols that prevent third parties or the general public from accessing private messages.
3434

3535
*Which cryptography technology is most widely used in blockchain and why?*
3636

37-
So, in general, blockchain technology is a distributed record holder which records the information about ownership of an asset. To define precisely,
37+
So, in general, blockchain technology is a distributed record holder that records the information about ownership of an asset. To define precisely,
3838
> Blockchain is a distributed, immutable ledger that makes it easier to record transactions and track assets in a corporate network.
3939
An asset could be tangible (such as a house, car, cash, or land) or intangible (such as a business) (intellectual property, patents, copyrights, branding). A blockchain network can track and sell almost anything of value, lowering risk and costs for everyone involved.
4040

41-
So this is all about introduction to blockchain technology. To learn more about the topic refer below links....
41+
So this is all about the introduction to blockchain technology. To learn more about the topic refer below links....
4242
* <https://en.wikipedia.org/wiki/Blockchain>
4343
* <https://en.wikipedia.org/wiki/Chinese_remainder_theorem>
4444
* <https://en.wikipedia.org/wiki/Diophantine_equation>
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
"""
2+
Assumption:
3+
- The values to compress are assumed to be comparable,
4+
values can be sorted and compared with '<' and '>' operators.
5+
"""
6+
7+
8+
class CoordinateCompressor:
9+
"""
10+
A class for coordinate compression.
11+
12+
This class allows you to compress and decompress a list of values.
13+
14+
Mapping:
15+
In addition to compression and decompression, this class maintains a mapping
16+
between original values and their compressed counterparts using two data
17+
structures: a dictionary `coordinate_map` and a list `reverse_map`:
18+
- `coordinate_map`: A dictionary that maps original values to their compressed
19+
coordinates. Keys are original values, and values are compressed coordinates.
20+
- `reverse_map`: A list used for reverse mapping, where each index corresponds
21+
to a compressed coordinate, and the value at that index is the original value.
22+
23+
Example of mapping:
24+
Original: 10, Compressed: 0
25+
Original: 52, Compressed: 1
26+
Original: 83, Compressed: 2
27+
Original: 100, Compressed: 3
28+
29+
This mapping allows for efficient compression and decompression of values within
30+
the list.
31+
"""
32+
33+
def __init__(self, arr: list[int | float | str]) -> None:
34+
"""
35+
Initialize the CoordinateCompressor with a list.
36+
37+
Args:
38+
arr: The list of values to be compressed.
39+
40+
>>> arr = [100, 10, 52, 83]
41+
>>> cc = CoordinateCompressor(arr)
42+
>>> cc.compress(100)
43+
3
44+
>>> cc.compress(52)
45+
1
46+
>>> cc.decompress(1)
47+
52
48+
"""
49+
50+
# A dictionary to store compressed coordinates
51+
self.coordinate_map: dict[int | float | str, int] = {}
52+
53+
# A list to store reverse mapping
54+
self.reverse_map: list[int | float | str] = [-1] * len(arr)
55+
56+
self.arr = sorted(arr) # The input list
57+
self.n = len(arr) # The length of the input list
58+
self.compress_coordinates()
59+
60+
def compress_coordinates(self) -> None:
61+
"""
62+
Compress the coordinates in the input list.
63+
64+
>>> arr = [100, 10, 52, 83]
65+
>>> cc = CoordinateCompressor(arr)
66+
>>> cc.coordinate_map[83]
67+
2
68+
>>> cc.coordinate_map[80] # Value not in the original list
69+
Traceback (most recent call last):
70+
...
71+
KeyError: 80
72+
>>> cc.reverse_map[2]
73+
83
74+
"""
75+
key = 0
76+
for val in self.arr:
77+
if val not in self.coordinate_map:
78+
self.coordinate_map[val] = key
79+
self.reverse_map[key] = val
80+
key += 1
81+
82+
def compress(self, original: float | str) -> int:
83+
"""
84+
Compress a single value.
85+
86+
Args:
87+
original: The value to compress.
88+
89+
Returns:
90+
The compressed integer, or -1 if not found in the original list.
91+
92+
>>> arr = [100, 10, 52, 83]
93+
>>> cc = CoordinateCompressor(arr)
94+
>>> cc.compress(100)
95+
3
96+
>>> cc.compress(7) # Value not in the original list
97+
-1
98+
"""
99+
return self.coordinate_map.get(original, -1)
100+
101+
def decompress(self, num: int) -> int | float | str:
102+
"""
103+
Decompress a single integer.
104+
105+
Args:
106+
num: The compressed integer to decompress.
107+
108+
Returns:
109+
The original value.
110+
111+
>>> arr = [100, 10, 52, 83]
112+
>>> cc = CoordinateCompressor(arr)
113+
>>> cc.decompress(0)
114+
10
115+
>>> cc.decompress(5) # Compressed coordinate out of range
116+
-1
117+
"""
118+
return self.reverse_map[num] if 0 <= num < len(self.reverse_map) else -1
119+
120+
121+
if __name__ == "__main__":
122+
from doctest import testmod
123+
124+
testmod()
125+
126+
arr: list[int | float | str] = [100, 10, 52, 83]
127+
cc = CoordinateCompressor(arr)
128+
129+
for original in arr:
130+
compressed = cc.compress(original)
131+
decompressed = cc.decompress(compressed)
132+
print(f"Original: {decompressed}, Compressed: {compressed}")

data_structures/binary_tree/binary_tree_path_sum.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,26 @@ class BinaryTreePathSum:
5050
>>> tree.right.right = Node(10)
5151
>>> BinaryTreePathSum().path_sum(tree, 8)
5252
2
53+
>>> BinaryTreePathSum().path_sum(None, 0)
54+
0
55+
>>> BinaryTreePathSum().path_sum(tree, 0)
56+
0
57+
58+
The second tree looks like this
59+
0
60+
/ \
61+
5 5
62+
63+
>>> tree2 = Node(0)
64+
>>> tree2.left = Node(5)
65+
>>> tree2.right = Node(5)
66+
67+
>>> BinaryTreePathSum().path_sum(tree2, 5)
68+
4
69+
>>> BinaryTreePathSum().path_sum(tree2, -1)
70+
0
71+
>>> BinaryTreePathSum().path_sum(tree2, 0)
72+
1
5373
"""
5474

5575
target: int

0 commit comments

Comments
 (0)