Skip to content

Commit 2750717

Browse files
authored
Merge branch 'TheAlgorithms:master' into patch-sparse
2 parents 01ee53a + 52040a7 commit 2750717

File tree

14 files changed

+748
-29
lines changed

14 files changed

+748
-29
lines changed

Diff for: DIRECTORY.md

+13-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,9 @@
6363

6464
## Boolean Algebra
6565
* [And Gate](boolean_algebra/and_gate.py)
66+
* [Imply Gate](boolean_algebra/imply_gate.py)
6667
* [Nand Gate](boolean_algebra/nand_gate.py)
68+
* [Nimply Gate](boolean_algebra/nimply_gate.py)
6769
* [Nor Gate](boolean_algebra/nor_gate.py)
6870
* [Not Gate](boolean_algebra/not_gate.py)
6971
* [Or Gate](boolean_algebra/or_gate.py)
@@ -119,9 +121,9 @@
119121
* [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py)
120122
* [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py)
121123
* [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py)
122-
* [Trafid Cipher](ciphers/trafid_cipher.py)
123124
* [Transposition Cipher](ciphers/transposition_cipher.py)
124125
* [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py)
126+
* [Trifid Cipher](ciphers/trifid_cipher.py)
125127
* [Vigenere Cipher](ciphers/vigenere_cipher.py)
126128
* [Xor Cipher](ciphers/xor_cipher.py)
127129

@@ -174,7 +176,9 @@
174176
## Data Structures
175177
* Arrays
176178
* [Equilibrium Index In Array](data_structures/arrays/equilibrium_index_in_array.py)
179+
* [Find Triplets With 0 Sum](data_structures/arrays/find_triplets_with_0_sum.py)
177180
* [Median Two Array](data_structures/arrays/median_two_array.py)
181+
* [Pairs With Given Sum](data_structures/arrays/pairs_with_given_sum.py)
178182
* [Permutations](data_structures/arrays/permutations.py)
179183
* [Prefix Sum](data_structures/arrays/prefix_sum.py)
180184
* [Product Sum](data_structures/arrays/product_sum.py)
@@ -385,6 +389,7 @@
385389

386390
## Financial
387391
* [Equated Monthly Installments](financial/equated_monthly_installments.py)
392+
* [Exponential Moving Average](financial/exponential_moving_average.py)
388393
* [Interest](financial/interest.py)
389394
* [Present Value](financial/present_value.py)
390395
* [Price Plus Tax](financial/price_plus_tax.py)
@@ -670,6 +675,7 @@
670675
* [Radians](maths/radians.py)
671676
* [Radix2 Fft](maths/radix2_fft.py)
672677
* [Remove Digit](maths/remove_digit.py)
678+
* [Rkf45](maths/rkf45.py)
673679
* [Runge Kutta](maths/runge_kutta.py)
674680
* [Segmented Sieve](maths/segmented_sieve.py)
675681
* Series
@@ -688,6 +694,7 @@
688694
* [Sin](maths/sin.py)
689695
* [Sock Merchant](maths/sock_merchant.py)
690696
* [Softmax](maths/softmax.py)
697+
* [Solovay Strassen Primality Test](maths/solovay_strassen_primality_test.py)
691698
* [Square Root](maths/square_root.py)
692699
* [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py)
693700
* [Sum Of Digits](maths/sum_of_digits.py)
@@ -728,6 +735,7 @@
728735
* [Spiral Print](matrix/spiral_print.py)
729736
* Tests
730737
* [Test Matrix Operation](matrix/tests/test_matrix_operation.py)
738+
* [Validate Sudoku Board](matrix/validate_sudoku_board.py)
731739

732740
## Networking Flow
733741
* [Ford Fulkerson](networking_flow/ford_fulkerson.py)
@@ -803,6 +811,7 @@
803811
* [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py)
804812
* [Shear Stress](physics/shear_stress.py)
805813
* [Speed Of Sound](physics/speed_of_sound.py)
814+
* [Speeds Of Gas Molecules](physics/speeds_of_gas_molecules.py)
806815

807816
## Project Euler
808817
* Problem 001
@@ -1106,6 +1115,7 @@
11061115
## Scheduling
11071116
* [First Come First Served](scheduling/first_come_first_served.py)
11081117
* [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py)
1118+
* [Job Sequence With Deadline](scheduling/job_sequence_with_deadline.py)
11091119
* [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py)
11101120
* [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py)
11111121
* [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py)
@@ -1193,6 +1203,7 @@
11931203
* [Capitalize](strings/capitalize.py)
11941204
* [Check Anagrams](strings/check_anagrams.py)
11951205
* [Credit Card Validator](strings/credit_card_validator.py)
1206+
* [Damerau Levenshtein Distance](strings/damerau_levenshtein_distance.py)
11961207
* [Detecting English Programmatically](strings/detecting_english_programmatically.py)
11971208
* [Dna](strings/dna.py)
11981209
* [Frequency Finder](strings/frequency_finder.py)
@@ -1225,6 +1236,7 @@
12251236
* [String Switch Case](strings/string_switch_case.py)
12261237
* [Strip](strings/strip.py)
12271238
* [Text Justification](strings/text_justification.py)
1239+
* [Title](strings/title.py)
12281240
* [Top K Frequent Words](strings/top_k_frequent_words.py)
12291241
* [Upper](strings/upper.py)
12301242
* [Wave](strings/wave.py)

Diff for: bit_manipulation/missing_number.py

+11-4
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,18 @@ def find_missing_number(nums: list[int]) -> int:
1111
Example:
1212
>>> find_missing_number([0, 1, 3, 4])
1313
2
14+
>>> find_missing_number([1, 3, 4, 5, 6])
15+
2
16+
>>> find_missing_number([6, 5, 4, 2, 1])
17+
3
18+
>>> find_missing_number([6, 1, 5, 3, 4])
19+
2
1420
"""
15-
n = len(nums)
16-
missing_number = n
21+
low = min(nums)
22+
high = max(nums)
23+
missing_number = high
1724

18-
for i in range(n):
19-
missing_number ^= i ^ nums[i]
25+
for i in range(low, high):
26+
missing_number ^= i ^ nums[i - low]
2027

2128
return missing_number
File renamed without changes.

Diff for: electronics/ic_555_timer.py

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
from __future__ import annotations
2+
3+
"""
4+
Calculate the frequency and/or duty cycle of an astable 555 timer.
5+
* https://en.wikipedia.org/wiki/555_timer_IC#Astable
6+
7+
These functions take in the value of the external resistances (in ohms)
8+
and capacitance (in Microfarad), and calculates the following:
9+
10+
-------------------------------------
11+
| Freq = 1.44 /[( R1+ 2 x R2) x C1] | ... in Hz
12+
-------------------------------------
13+
where Freq is the frequency,
14+
R1 is the first resistance in ohms,
15+
R2 is the second resistance in ohms,
16+
C1 is the capacitance in Microfarads.
17+
18+
------------------------------------------------
19+
| Duty Cycle = (R1 + R2) / (R1 + 2 x R2) x 100 | ... in %
20+
------------------------------------------------
21+
where R1 is the first resistance in ohms,
22+
R2 is the second resistance in ohms.
23+
"""
24+
25+
26+
def astable_frequency(
27+
resistance_1: float, resistance_2: float, capacitance: float
28+
) -> float:
29+
"""
30+
Usage examples:
31+
>>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=7)
32+
1523.8095238095239
33+
>>> astable_frequency(resistance_1=356, resistance_2=234, capacitance=976)
34+
1.7905459175553078
35+
>>> astable_frequency(resistance_1=2, resistance_2=-1, capacitance=2)
36+
Traceback (most recent call last):
37+
...
38+
ValueError: All values must be positive
39+
>>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=0)
40+
Traceback (most recent call last):
41+
...
42+
ValueError: All values must be positive
43+
"""
44+
45+
if resistance_1 <= 0 or resistance_2 <= 0 or capacitance <= 0:
46+
raise ValueError("All values must be positive")
47+
return (1.44 / ((resistance_1 + 2 * resistance_2) * capacitance)) * 10**6
48+
49+
50+
def astable_duty_cycle(resistance_1: float, resistance_2: float) -> float:
51+
"""
52+
Usage examples:
53+
>>> astable_duty_cycle(resistance_1=45, resistance_2=45)
54+
66.66666666666666
55+
>>> astable_duty_cycle(resistance_1=356, resistance_2=234)
56+
71.60194174757282
57+
>>> astable_duty_cycle(resistance_1=2, resistance_2=-1)
58+
Traceback (most recent call last):
59+
...
60+
ValueError: All values must be positive
61+
>>> astable_duty_cycle(resistance_1=0, resistance_2=0)
62+
Traceback (most recent call last):
63+
...
64+
ValueError: All values must be positive
65+
"""
66+
67+
if resistance_1 <= 0 or resistance_2 <= 0:
68+
raise ValueError("All values must be positive")
69+
return (resistance_1 + resistance_2) / (resistance_1 + 2 * resistance_2) * 100
70+
71+
72+
if __name__ == "__main__":
73+
import doctest
74+
75+
doctest.testmod()

Diff for: maths/joint_probability_distribution.py

+124
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
"""
2+
Calculate joint probability distribution
3+
https://en.wikipedia.org/wiki/Joint_probability_distribution
4+
"""
5+
6+
7+
def joint_probability_distribution(
8+
x_values: list[int],
9+
y_values: list[int],
10+
x_probabilities: list[float],
11+
y_probabilities: list[float],
12+
) -> dict:
13+
"""
14+
>>> joint_distribution = joint_probability_distribution(
15+
... [1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2]
16+
... )
17+
>>> from math import isclose
18+
>>> isclose(joint_distribution.pop((1, 8)), 0.14)
19+
True
20+
>>> joint_distribution
21+
{(1, -2): 0.21, (1, 5): 0.35, (2, -2): 0.09, (2, 5): 0.15, (2, 8): 0.06}
22+
"""
23+
return {
24+
(x, y): x_prob * y_prob
25+
for x, x_prob in zip(x_values, x_probabilities)
26+
for y, y_prob in zip(y_values, y_probabilities)
27+
}
28+
29+
30+
# Function to calculate the expectation (mean)
31+
def expectation(values: list, probabilities: list) -> float:
32+
"""
33+
>>> from math import isclose
34+
>>> isclose(expectation([1, 2], [0.7, 0.3]), 1.3)
35+
True
36+
"""
37+
return sum(x * p for x, p in zip(values, probabilities))
38+
39+
40+
# Function to calculate the variance
41+
def variance(values: list[int], probabilities: list[float]) -> float:
42+
"""
43+
>>> from math import isclose
44+
>>> isclose(variance([1,2],[0.7,0.3]), 0.21)
45+
True
46+
"""
47+
mean = expectation(values, probabilities)
48+
return sum((x - mean) ** 2 * p for x, p in zip(values, probabilities))
49+
50+
51+
# Function to calculate the covariance
52+
def covariance(
53+
x_values: list[int],
54+
y_values: list[int],
55+
x_probabilities: list[float],
56+
y_probabilities: list[float],
57+
) -> float:
58+
"""
59+
>>> covariance([1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2])
60+
-2.7755575615628914e-17
61+
"""
62+
mean_x = expectation(x_values, x_probabilities)
63+
mean_y = expectation(y_values, y_probabilities)
64+
return sum(
65+
(x - mean_x) * (y - mean_y) * px * py
66+
for x, px in zip(x_values, x_probabilities)
67+
for y, py in zip(y_values, y_probabilities)
68+
)
69+
70+
71+
# Function to calculate the standard deviation
72+
def standard_deviation(variance: float) -> float:
73+
"""
74+
>>> standard_deviation(0.21)
75+
0.458257569495584
76+
"""
77+
return variance**0.5
78+
79+
80+
if __name__ == "__main__":
81+
from doctest import testmod
82+
83+
testmod()
84+
# Input values for X and Y
85+
x_vals = input("Enter values of X separated by spaces: ").split()
86+
y_vals = input("Enter values of Y separated by spaces: ").split()
87+
88+
# Convert input values to integers
89+
x_values = [int(x) for x in x_vals]
90+
y_values = [int(y) for y in y_vals]
91+
92+
# Input probabilities for X and Y
93+
x_probs = input("Enter probabilities for X separated by spaces: ").split()
94+
y_probs = input("Enter probabilities for Y separated by spaces: ").split()
95+
assert len(x_values) == len(x_probs)
96+
assert len(y_values) == len(y_probs)
97+
98+
# Convert input probabilities to floats
99+
x_probabilities = [float(p) for p in x_probs]
100+
y_probabilities = [float(p) for p in y_probs]
101+
102+
# Calculate the joint probability distribution
103+
jpd = joint_probability_distribution(
104+
x_values, y_values, x_probabilities, y_probabilities
105+
)
106+
107+
# Print the joint probability distribution
108+
print(
109+
"\n".join(
110+
f"P(X={x}, Y={y}) = {probability}" for (x, y), probability in jpd.items()
111+
)
112+
)
113+
mean_xy = expectation(
114+
[x * y for x in x_values for y in y_values],
115+
[px * py for px in x_probabilities for py in y_probabilities],
116+
)
117+
print(f"x mean: {expectation(x_values, x_probabilities) = }")
118+
print(f"y mean: {expectation(y_values, y_probabilities) = }")
119+
print(f"xy mean: {mean_xy}")
120+
print(f"x: {variance(x_values, x_probabilities) = }")
121+
print(f"y: {variance(y_values, y_probabilities) = }")
122+
print(f"{covariance(x_values, y_values, x_probabilities, y_probabilities) = }")
123+
print(f"x: {standard_deviation(variance(x_values, x_probabilities)) = }")
124+
print(f"y: {standard_deviation(variance(y_values, y_probabilities)) = }")

0 commit comments

Comments
 (0)