Skip to content

Commit 9dc4645

Browse files
authored
Merge branch 'TheAlgorithms:master' into master
2 parents 23ef488 + 0e3ea3f commit 9dc4645

File tree

7 files changed

+281
-2
lines changed

7 files changed

+281
-2
lines changed

Diff for: CONTRIBUTING.md

+4
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,12 @@ We appreciate any contribution, from fixing a grammar mistake in a comment to im
2525

2626
Your contribution will be tested by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) to save time and mental energy. After you have submitted your pull request, you should see the GitHub Actions tests start to run at the bottom of your submission page. If those tests fail, then click on the ___details___ button try to read through the GitHub Actions output to understand the failure. If you do not understand, please leave a comment on your submission page and a community member will try to help.
2727

28+
#### Issues
29+
2830
If you are interested in resolving an [open issue](https://github.com/TheAlgorithms/Python/issues), simply make a pull request with your proposed fix. __We do not assign issues in this repo__ so please do not ask for permission to work on an issue.
2931

32+
__Do not__ create an issue to contribute an algorithm. Please submit a pull request instead.
33+
3034
Please help us keep our issue list small by adding `Fixes #{$ISSUE_NUMBER}` to the description of pull requests that resolve open issues.
3135
For example, if your pull request fixes issue #10, then please add the following to its description:
3236
```

Diff for: DIRECTORY.md

+9-1
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@
170170

171171
## Data Structures
172172
* Arrays
173+
* [Median Two Array](data_structures/arrays/median_two_array.py)
173174
* [Permutations](data_structures/arrays/permutations.py)
174175
* [Prefix Sum](data_structures/arrays/prefix_sum.py)
175176
* [Product Sum](data_structures/arrays/product_sum.py)
@@ -185,6 +186,7 @@
185186
* [Diff Views Of Binary Tree](data_structures/binary_tree/diff_views_of_binary_tree.py)
186187
* [Distribute Coins](data_structures/binary_tree/distribute_coins.py)
187188
* [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py)
189+
* [Flatten Binarytree To Linkedlist](data_structures/binary_tree/flatten_binarytree_to_linkedlist.py)
188190
* [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py)
189191
* [Is Bst](data_structures/binary_tree/is_bst.py)
190192
* [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py)
@@ -324,6 +326,7 @@
324326
* [Longest Common Substring](dynamic_programming/longest_common_substring.py)
325327
* [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py)
326328
* [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py)
329+
* [Longest Palindromic Subsequence](dynamic_programming/longest_palindromic_subsequence.py)
327330
* [Longest Sub Array](dynamic_programming/longest_sub_array.py)
328331
* [Matrix Chain Order](dynamic_programming/matrix_chain_order.py)
329332
* [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py)
@@ -466,6 +469,7 @@
466469
* [Djb2](hashes/djb2.py)
467470
* [Elf](hashes/elf.py)
468471
* [Enigma Machine](hashes/enigma_machine.py)
472+
* [Fletcher16](hashes/fletcher16.py)
469473
* [Hamming Code](hashes/hamming_code.py)
470474
* [Luhn](hashes/luhn.py)
471475
* [Md5](hashes/md5.py)
@@ -539,6 +543,7 @@
539543
* [Average Mode](maths/average_mode.py)
540544
* [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py)
541545
* [Basic Maths](maths/basic_maths.py)
546+
* [Bell Numbers](maths/bell_numbers.py)
542547
* [Binary Exp Mod](maths/binary_exp_mod.py)
543548
* [Binary Exponentiation](maths/binary_exponentiation.py)
544549
* [Binary Exponentiation 3](maths/binary_exponentiation_3.py)
@@ -690,6 +695,7 @@
690695
* [Matrix Class](matrix/matrix_class.py)
691696
* [Matrix Operation](matrix/matrix_operation.py)
692697
* [Max Area Of Island](matrix/max_area_of_island.py)
698+
* [Median Matrix](matrix/median_matrix.py)
693699
* [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py)
694700
* [Pascal Triangle](matrix/pascal_triangle.py)
695701
* [Rotate Matrix](matrix/rotate_matrix.py)
@@ -708,8 +714,8 @@
708714
* Activation Functions
709715
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
710716
* [Leaky Rectified Linear Unit](neural_network/activation_functions/leaky_rectified_linear_unit.py)
711-
* [Scaled Exponential Linear Unit](neural_network/activation_functions/scaled_exponential_linear_unit.py)
712717
* [Rectified Linear Unit](neural_network/activation_functions/rectified_linear_unit.py)
718+
* [Scaled Exponential Linear Unit](neural_network/activation_functions/scaled_exponential_linear_unit.py)
713719
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
714720
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
715721
* [Perceptron](neural_network/perceptron.py)
@@ -756,9 +762,11 @@
756762
* [Kinetic Energy](physics/kinetic_energy.py)
757763
* [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py)
758764
* [Malus Law](physics/malus_law.py)
765+
* [Mirror Formulae](physics/mirror_formulae.py)
759766
* [N Body Simulation](physics/n_body_simulation.py)
760767
* [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py)
761768
* [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)
769+
* [Photoelectric Effect](physics/photoelectric_effect.py)
762770
* [Potential Energy](physics/potential_energy.py)
763771
* [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py)
764772
* [Shear Stress](physics/shear_stress.py)

Diff for: bit_manipulation/largest_pow_of_two_le_num.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Author : Naman Sharma
3+
Date : October 2, 2023
4+
5+
Task:
6+
To Find the largest power of 2 less than or equal to a given number.
7+
8+
Implementation notes: Use bit manipulation.
9+
We start from 1 & left shift the set bit to check if (res<<1)<=number.
10+
Each left bit shift represents a pow of 2.
11+
12+
For example:
13+
number: 15
14+
res: 1 0b1
15+
2 0b10
16+
4 0b100
17+
8 0b1000
18+
16 0b10000 (Exit)
19+
"""
20+
21+
22+
def largest_pow_of_two_le_num(number: int) -> int:
23+
"""
24+
Return the largest power of two less than or equal to a number.
25+
26+
>>> largest_pow_of_two_le_num(0)
27+
0
28+
>>> largest_pow_of_two_le_num(1)
29+
1
30+
>>> largest_pow_of_two_le_num(-1)
31+
0
32+
>>> largest_pow_of_two_le_num(3)
33+
2
34+
>>> largest_pow_of_two_le_num(15)
35+
8
36+
>>> largest_pow_of_two_le_num(99)
37+
64
38+
>>> largest_pow_of_two_le_num(178)
39+
128
40+
>>> largest_pow_of_two_le_num(999999)
41+
524288
42+
>>> largest_pow_of_two_le_num(99.9)
43+
Traceback (most recent call last):
44+
...
45+
TypeError: Input value must be a 'int' type
46+
"""
47+
if isinstance(number, float):
48+
raise TypeError("Input value must be a 'int' type")
49+
if number <= 0:
50+
return 0
51+
res = 1
52+
while (res << 1) <= number:
53+
res <<= 1
54+
return res
55+
56+
57+
if __name__ == "__main__":
58+
import doctest
59+
60+
doctest.testmod()

Diff for: hashes/fletcher16.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
The Fletcher checksum is an algorithm for computing a position-dependent
3+
checksum devised by John G. Fletcher (1934–2012) at Lawrence Livermore Labs
4+
in the late 1970s.[1] The objective of the Fletcher checksum was to
5+
provide error-detection properties approaching those of a cyclic
6+
redundancy check but with the lower computational effort associated
7+
with summation techniques.
8+
9+
Source: https://en.wikipedia.org/wiki/Fletcher%27s_checksum
10+
"""
11+
12+
13+
def fletcher16(text: str) -> int:
14+
"""
15+
Loop through every character in the data and add to two sums.
16+
17+
>>> fletcher16('hello world')
18+
6752
19+
>>> fletcher16('onethousandfourhundredthirtyfour')
20+
28347
21+
>>> fletcher16('The quick brown fox jumps over the lazy dog.')
22+
5655
23+
"""
24+
data = bytes(text, "ascii")
25+
sum1 = 0
26+
sum2 = 0
27+
for character in data:
28+
sum1 = (sum1 + character) % 255
29+
sum2 = (sum1 + sum2) % 255
30+
return (sum2 << 8) | sum1
31+
32+
33+
if __name__ == "__main__":
34+
import doctest
35+
36+
doctest.testmod()

Diff for: maths/fermat_little_theorem.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
# Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem
66

77

8-
def binary_exponentiation(a, n, mod):
8+
def binary_exponentiation(a: int, n: float, mod: int) -> int:
99
if n == 0:
1010
return 1
1111

Diff for: physics/mirror_formulae.py

+127
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
"""
2+
This module contains the functions to calculate the focal length, object distance
3+
and image distance of a mirror.
4+
5+
The mirror formula is an equation that relates the object distance (u),
6+
image distance (v), and focal length (f) of a spherical mirror.
7+
It is commonly used in optics to determine the position and characteristics
8+
of an image formed by a mirror. It is expressed using the formulae :
9+
10+
-------------------
11+
| 1/f = 1/v + 1/u |
12+
-------------------
13+
14+
Where,
15+
f = Focal length of the spherical mirror (metre)
16+
v = Image distance from the mirror (metre)
17+
u = Object distance from the mirror (metre)
18+
19+
20+
The signs of the distances are taken with respect to the sign convention.
21+
The sign convention is as follows:
22+
1) Object is always placed to the left of mirror
23+
2) Distances measured in the direction of the incident ray are positive
24+
and the distances measured in the direction opposite to that of the incident
25+
rays are negative.
26+
3) All distances are measured from the pole of the mirror.
27+
28+
29+
There are a few assumptions that are made while using the mirror formulae.
30+
They are as follows:
31+
1) Thin Mirror: The mirror is assumed to be thin, meaning its thickness is
32+
negligible compared to its radius of curvature. This assumption allows
33+
us to treat the mirror as a two-dimensional surface.
34+
2) Spherical Mirror: The mirror is assumed to have a spherical shape. While this
35+
assumption may not hold exactly for all mirrors, it is a reasonable approximation
36+
for most practical purposes.
37+
3) Small Angles: The angles involved in the derivation are assumed to be small.
38+
This assumption allows us to use the small-angle approximation, where the tangent
39+
of a small angle is approximately equal to the angle itself. It simplifies the
40+
calculations and makes the derivation more manageable.
41+
4) Paraxial Rays: The mirror formula is derived using paraxial rays, which are
42+
rays that are close to the principal axis and make small angles with it. This
43+
assumption ensures that the rays are close enough to the principal axis, making the
44+
calculations more accurate.
45+
5) Reflection and Refraction Laws: The derivation assumes that the laws of
46+
reflection and refraction hold.
47+
These laws state that the angle of incidence is equal to the angle of reflection
48+
for reflection, and the incident and refracted rays lie in the same plane and
49+
obey Snell's law for refraction.
50+
51+
(Description and Assumptions adapted from
52+
https://www.collegesearch.in/articles/mirror-formula-derivation)
53+
54+
(Sign Convention adapted from
55+
https://www.toppr.com/ask/content/concept/sign-convention-for-mirrors-210189/)
56+
57+
58+
"""
59+
60+
61+
def focal_length(distance_of_object: float, distance_of_image: float) -> float:
62+
"""
63+
>>> from math import isclose
64+
>>> isclose(focal_length(10, 20), 6.66666666666666)
65+
True
66+
>>> from math import isclose
67+
>>> isclose(focal_length(9.5, 6.7), 3.929012346)
68+
True
69+
>>> focal_length(0, 20) # doctest: +NORMALIZE_WHITESPACE
70+
Traceback (most recent call last):
71+
...
72+
ValueError: Invalid inputs. Enter non zero values with respect
73+
to the sign convention.
74+
"""
75+
76+
if distance_of_object == 0 or distance_of_image == 0:
77+
raise ValueError(
78+
"Invalid inputs. Enter non zero values with respect to the sign convention."
79+
)
80+
focal_length = 1 / ((1 / distance_of_object) + (1 / distance_of_image))
81+
return focal_length
82+
83+
84+
def object_distance(focal_length: float, distance_of_image: float) -> float:
85+
"""
86+
>>> from math import isclose
87+
>>> isclose(object_distance(30, 20), -60.0)
88+
True
89+
>>> from math import isclose
90+
>>> isclose(object_distance(10.5, 11.7), 102.375)
91+
True
92+
>>> object_distance(90, 0) # doctest: +NORMALIZE_WHITESPACE
93+
Traceback (most recent call last):
94+
...
95+
ValueError: Invalid inputs. Enter non zero values with respect
96+
to the sign convention.
97+
"""
98+
99+
if distance_of_image == 0 or focal_length == 0:
100+
raise ValueError(
101+
"Invalid inputs. Enter non zero values with respect to the sign convention."
102+
)
103+
object_distance = 1 / ((1 / focal_length) - (1 / distance_of_image))
104+
return object_distance
105+
106+
107+
def image_distance(focal_length: float, distance_of_object: float) -> float:
108+
"""
109+
>>> from math import isclose
110+
>>> isclose(image_distance(10, 40), 13.33333333)
111+
True
112+
>>> from math import isclose
113+
>>> isclose(image_distance(1.5, 6.7), 1.932692308)
114+
True
115+
>>> image_distance(0, 0) # doctest: +NORMALIZE_WHITESPACE
116+
Traceback (most recent call last):
117+
...
118+
ValueError: Invalid inputs. Enter non zero values with respect
119+
to the sign convention.
120+
"""
121+
122+
if distance_of_object == 0 or focal_length == 0:
123+
raise ValueError(
124+
"Invalid inputs. Enter non zero values with respect to the sign convention."
125+
)
126+
image_distance = 1 / ((1 / focal_length) - (1 / distance_of_object))
127+
return image_distance

Diff for: strings/pig_latin.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
def pig_latin(word: str) -> str:
2+
"""Compute the piglatin of a given string.
3+
4+
https://en.wikipedia.org/wiki/Pig_Latin
5+
6+
Usage examples:
7+
>>> pig_latin("pig")
8+
'igpay'
9+
>>> pig_latin("latin")
10+
'atinlay'
11+
>>> pig_latin("banana")
12+
'ananabay'
13+
>>> pig_latin("friends")
14+
'iendsfray'
15+
>>> pig_latin("smile")
16+
'ilesmay'
17+
>>> pig_latin("string")
18+
'ingstray'
19+
>>> pig_latin("eat")
20+
'eatway'
21+
>>> pig_latin("omelet")
22+
'omeletway'
23+
>>> pig_latin("are")
24+
'areway'
25+
>>> pig_latin(" ")
26+
''
27+
>>> pig_latin(None)
28+
''
29+
"""
30+
if not (word or "").strip():
31+
return ""
32+
word = word.lower()
33+
if word[0] in "aeiou":
34+
return f"{word}way"
35+
for i, char in enumerate(word): # noqa: B007
36+
if char in "aeiou":
37+
break
38+
return f"{word[i:]}{word[:i]}ay"
39+
40+
41+
if __name__ == "__main__":
42+
print(f"{pig_latin('friends') = }")
43+
word = input("Enter a word: ")
44+
print(f"{pig_latin(word) = }")

0 commit comments

Comments
 (0)