Skip to content

Commit e85e96b

Browse files
authored
Merge branch 'TheAlgorithms:master' into master
2 parents 3ed93d8 + ed19b1c commit e85e96b

45 files changed

Lines changed: 1196 additions & 164 deletions

Some content is hidden

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

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ repos:
2626
- id: black
2727

2828
- repo: https://github.com/codespell-project/codespell
29-
rev: v2.2.5
29+
rev: v2.2.6
3030
hooks:
3131
- id: codespell
3232
additional_dependencies:

DIRECTORY.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,7 @@
556556
* [Bell Numbers](maths/bell_numbers.py)
557557
* [Binary Exp Mod](maths/binary_exp_mod.py)
558558
* [Binary Exponentiation](maths/binary_exponentiation.py)
559-
* [Binary Exponentiation 3](maths/binary_exponentiation_3.py)
559+
* [Binary Exponentiation 2](maths/binary_exponentiation_2.py)
560560
* [Binary Multiplication](maths/binary_multiplication.py)
561561
* [Binomial Coefficient](maths/binomial_coefficient.py)
562562
* [Binomial Distribution](maths/binomial_distribution.py)
@@ -588,7 +588,6 @@
588588
* [Find Min](maths/find_min.py)
589589
* [Floor](maths/floor.py)
590590
* [Gamma](maths/gamma.py)
591-
* [Gamma Recursive](maths/gamma_recursive.py)
592591
* [Gaussian](maths/gaussian.py)
593592
* [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py)
594593
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
@@ -723,6 +722,7 @@
723722
* Activation Functions
724723
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
725724
* [Leaky Rectified Linear Unit](neural_network/activation_functions/leaky_rectified_linear_unit.py)
725+
* [Mish](neural_network/activation_functions/mish.py)
726726
* [Rectified Linear Unit](neural_network/activation_functions/rectified_linear_unit.py)
727727
* [Scaled Exponential Linear Unit](neural_network/activation_functions/scaled_exponential_linear_unit.py)
728728
* [Sigmoid Linear Unit](neural_network/activation_functions/sigmoid_linear_unit.py)
@@ -748,6 +748,7 @@
748748
* [Linear Congruential Generator](other/linear_congruential_generator.py)
749749
* [Lru Cache](other/lru_cache.py)
750750
* [Magicdiamondpattern](other/magicdiamondpattern.py)
751+
* [Majority Vote Algorithm](other/majority_vote_algorithm.py)
751752
* [Maximum Subsequence](other/maximum_subsequence.py)
752753
* [Nested Brackets](other/nested_brackets.py)
753754
* [Number Container System](other/number_container_system.py)
@@ -1196,7 +1197,6 @@
11961197
* [Rabin Karp](strings/rabin_karp.py)
11971198
* [Remove Duplicate](strings/remove_duplicate.py)
11981199
* [Reverse Letters](strings/reverse_letters.py)
1199-
* [Reverse Long Words](strings/reverse_long_words.py)
12001200
* [Reverse Words](strings/reverse_words.py)
12011201
* [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py)
12021202
* [Split](strings/split.py)

bit_manipulation/power_of_4.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
3+
Task:
4+
Given a positive int number. Return True if this number is power of 4
5+
or False otherwise.
6+
7+
Implementation notes: Use bit manipulation.
8+
For example if the number is the power of 2 it's bits representation:
9+
n = 0..100..00
10+
n - 1 = 0..011..11
11+
12+
n & (n - 1) - no intersections = 0
13+
If the number is a power of 4 then it should be a power of 2
14+
and the set bit should be at an odd position.
15+
"""
16+
17+
18+
def power_of_4(number: int) -> bool:
19+
"""
20+
Return True if this number is power of 4 or False otherwise.
21+
22+
>>> power_of_4(0)
23+
Traceback (most recent call last):
24+
...
25+
ValueError: number must be positive
26+
>>> power_of_4(1)
27+
True
28+
>>> power_of_4(2)
29+
False
30+
>>> power_of_4(4)
31+
True
32+
>>> power_of_4(6)
33+
False
34+
>>> power_of_4(8)
35+
False
36+
>>> power_of_4(17)
37+
False
38+
>>> power_of_4(64)
39+
True
40+
>>> power_of_4(-1)
41+
Traceback (most recent call last):
42+
...
43+
ValueError: number must be positive
44+
>>> power_of_4(1.2)
45+
Traceback (most recent call last):
46+
...
47+
TypeError: number must be an integer
48+
49+
"""
50+
if not isinstance(number, int):
51+
raise TypeError("number must be an integer")
52+
if number <= 0:
53+
raise ValueError("number must be positive")
54+
if number & (number - 1) == 0:
55+
c = 0
56+
while number:
57+
c += 1
58+
number >>= 1
59+
return c % 2 == 1
60+
else:
61+
return False
62+
63+
64+
if __name__ == "__main__":
65+
import doctest
66+
67+
doctest.testmod()
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
"""
2+
Python program for the Fractionated Morse Cipher.
3+
4+
The Fractionated Morse cipher first converts the plaintext to Morse code,
5+
then enciphers fixed-size blocks of Morse code back to letters.
6+
This procedure means plaintext letters are mixed into the ciphertext letters,
7+
making it more secure than substitution ciphers.
8+
9+
http://practicalcryptography.com/ciphers/fractionated-morse-cipher/
10+
"""
11+
import string
12+
13+
MORSE_CODE_DICT = {
14+
"A": ".-",
15+
"B": "-...",
16+
"C": "-.-.",
17+
"D": "-..",
18+
"E": ".",
19+
"F": "..-.",
20+
"G": "--.",
21+
"H": "....",
22+
"I": "..",
23+
"J": ".---",
24+
"K": "-.-",
25+
"L": ".-..",
26+
"M": "--",
27+
"N": "-.",
28+
"O": "---",
29+
"P": ".--.",
30+
"Q": "--.-",
31+
"R": ".-.",
32+
"S": "...",
33+
"T": "-",
34+
"U": "..-",
35+
"V": "...-",
36+
"W": ".--",
37+
"X": "-..-",
38+
"Y": "-.--",
39+
"Z": "--..",
40+
" ": "",
41+
}
42+
43+
# Define possible trigrams of Morse code
44+
MORSE_COMBINATIONS = [
45+
"...",
46+
"..-",
47+
"..x",
48+
".-.",
49+
".--",
50+
".-x",
51+
".x.",
52+
".x-",
53+
".xx",
54+
"-..",
55+
"-.-",
56+
"-.x",
57+
"--.",
58+
"---",
59+
"--x",
60+
"-x.",
61+
"-x-",
62+
"-xx",
63+
"x..",
64+
"x.-",
65+
"x.x",
66+
"x-.",
67+
"x--",
68+
"x-x",
69+
"xx.",
70+
"xx-",
71+
"xxx",
72+
]
73+
74+
# Create a reverse dictionary for Morse code
75+
REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()}
76+
77+
78+
def encode_to_morse(plaintext: str) -> str:
79+
"""Encode a plaintext message into Morse code.
80+
81+
Args:
82+
plaintext: The plaintext message to encode.
83+
84+
Returns:
85+
The Morse code representation of the plaintext message.
86+
87+
Example:
88+
>>> encode_to_morse("defend the east")
89+
'-..x.x..-.x.x-.x-..xx-x....x.xx.x.-x...x-'
90+
"""
91+
return "x".join([MORSE_CODE_DICT.get(letter.upper(), "") for letter in plaintext])
92+
93+
94+
def encrypt_fractionated_morse(plaintext: str, key: str) -> str:
95+
"""Encrypt a plaintext message using Fractionated Morse Cipher.
96+
97+
Args:
98+
plaintext: The plaintext message to encrypt.
99+
key: The encryption key.
100+
101+
Returns:
102+
The encrypted ciphertext.
103+
104+
Example:
105+
>>> encrypt_fractionated_morse("defend the east","Roundtable")
106+
'ESOAVVLJRSSTRX'
107+
108+
"""
109+
morse_code = encode_to_morse(plaintext)
110+
key = key.upper() + string.ascii_uppercase
111+
key = "".join(sorted(set(key), key=key.find))
112+
113+
# Ensure morse_code length is a multiple of 3
114+
padding_length = 3 - (len(morse_code) % 3)
115+
morse_code += "x" * padding_length
116+
117+
fractionated_morse_dict = {v: k for k, v in zip(key, MORSE_COMBINATIONS)}
118+
fractionated_morse_dict["xxx"] = ""
119+
encrypted_text = "".join(
120+
[
121+
fractionated_morse_dict[morse_code[i : i + 3]]
122+
for i in range(0, len(morse_code), 3)
123+
]
124+
)
125+
return encrypted_text
126+
127+
128+
def decrypt_fractionated_morse(ciphertext: str, key: str) -> str:
129+
"""Decrypt a ciphertext message encrypted with Fractionated Morse Cipher.
130+
131+
Args:
132+
ciphertext: The ciphertext message to decrypt.
133+
key: The decryption key.
134+
135+
Returns:
136+
The decrypted plaintext message.
137+
138+
Example:
139+
>>> decrypt_fractionated_morse("ESOAVVLJRSSTRX","Roundtable")
140+
'DEFEND THE EAST'
141+
"""
142+
key = key.upper() + string.ascii_uppercase
143+
key = "".join(sorted(set(key), key=key.find))
144+
145+
inverse_fractionated_morse_dict = dict(zip(key, MORSE_COMBINATIONS))
146+
morse_code = "".join(
147+
[inverse_fractionated_morse_dict.get(letter, "") for letter in ciphertext]
148+
)
149+
decrypted_text = "".join(
150+
[REVERSE_DICT[code] for code in morse_code.split("x")]
151+
).strip()
152+
return decrypted_text
153+
154+
155+
if __name__ == "__main__":
156+
"""
157+
Example usage of Fractionated Morse Cipher.
158+
"""
159+
plaintext = "defend the east"
160+
print("Plain Text:", plaintext)
161+
key = "ROUNDTABLE"
162+
163+
ciphertext = encrypt_fractionated_morse(plaintext, key)
164+
print("Encrypted:", ciphertext)
165+
166+
decrypted_text = decrypt_fractionated_morse(ciphertext, key)
167+
print("Decrypted:", decrypted_text)

computer_vision/cnn_classification.py.DISABLED.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ Download dataset from :
1111
https://lhncbc.nlm.nih.gov/LHC-publications/pubs/TuberculosisChestXrayImageDataSets.html
1212

1313
1. Download the dataset folder and create two folder training set and test set
14-
in the parent dataste folder
14+
in the parent dataset folder
1515
2. Move 30-40 image from both TB positive and TB Negative folder
1616
in the test set folder
17-
3. The labels of the iamges will be extracted from the folder name
17+
3. The labels of the images will be extracted from the folder name
1818
the image is present in.
1919

2020
"""

computer_vision/mosaic_augmentation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import cv2
99
import numpy as np
1010

11-
# Parrameters
11+
# Parameters
1212
OUTPUT_SIZE = (720, 1280) # Height, Width
1313
SCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it.
1414
FILTER_TINY_SCALE = 1 / 100
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
Find the Equilibrium Index of an Array.
3+
Reference: https://www.geeksforgeeks.org/equilibrium-index-of-an-array/
4+
5+
Python doctests can be run with the following command:
6+
python -m doctest -v equilibrium_index.py
7+
8+
Given a sequence arr[] of size n, this function returns
9+
an equilibrium index (if any) or -1 if no equilibrium index exists.
10+
11+
The equilibrium index of an array is an index such that the sum of
12+
elements at lower indexes is equal to the sum of elements at higher indexes.
13+
14+
15+
16+
Example Input:
17+
arr = [-7, 1, 5, 2, -4, 3, 0]
18+
Output: 3
19+
20+
"""
21+
22+
23+
def equilibrium_index(arr: list[int], size: int) -> int:
24+
"""
25+
Find the equilibrium index of an array.
26+
27+
Args:
28+
arr : The input array of integers.
29+
size : The size of the array.
30+
31+
Returns:
32+
int: The equilibrium index or -1 if no equilibrium index exists.
33+
34+
Examples:
35+
>>> equilibrium_index([-7, 1, 5, 2, -4, 3, 0], 7)
36+
3
37+
>>> equilibrium_index([1, 2, 3, 4, 5], 5)
38+
-1
39+
>>> equilibrium_index([1, 1, 1, 1, 1], 5)
40+
2
41+
>>> equilibrium_index([2, 4, 6, 8, 10, 3], 6)
42+
-1
43+
"""
44+
total_sum = sum(arr)
45+
left_sum = 0
46+
47+
for i in range(size):
48+
total_sum -= arr[i]
49+
if left_sum == total_sum:
50+
return i
51+
left_sum += arr[i]
52+
53+
return -1
54+
55+
56+
if __name__ == "__main__":
57+
import doctest
58+
59+
doctest.testmod()

divide_and_conquer/strassen_matrix_multiplication.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def print_matrix(matrix: list) -> None:
7474
def actual_strassen(matrix_a: list, matrix_b: list) -> list:
7575
"""
7676
Recursive function to calculate the product of two matrices, using the Strassen
77-
Algorithm. It only supports even length matrices.
77+
Algorithm. It only supports square matrices of any size that is a power of 2.
7878
"""
7979
if matrix_dimensions(matrix_a) == (2, 2):
8080
return default_matrix_multiplication(matrix_a, matrix_b)
@@ -129,8 +129,8 @@ def strassen(matrix1: list, matrix2: list) -> list:
129129
new_matrix1 = matrix1
130130
new_matrix2 = matrix2
131131

132-
# Adding zeros to the matrices so that the arrays dimensions are the same and also
133-
# power of 2
132+
# Adding zeros to the matrices to convert them both into square matrices of equal
133+
# dimensions that are a power of 2
134134
for i in range(maxim):
135135
if i < dimension1[0]:
136136
for _ in range(dimension1[1], maxim):

0 commit comments

Comments
 (0)