Skip to content

Commit fccae1c

Browse files
Merge branch 'update_power_sum.py' of https://github.com/Muhammadummerr/Python into update_power_sum.py
2 parents ea380af + 0b1abca commit fccae1c

File tree

98 files changed

+2896
-701
lines changed

Some content is hidden

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

98 files changed

+2896
-701
lines changed

.pre-commit-config.yaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
repos:
22
- repo: https://github.com/pre-commit/pre-commit-hooks
3-
rev: v4.4.0
3+
rev: v4.5.0
44
hooks:
55
- id: check-executables-have-shebangs
66
- id: check-toml
@@ -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:
@@ -51,7 +51,7 @@ repos:
5151
- id: validate-pyproject
5252

5353
- repo: https://github.com/pre-commit/mirrors-mypy
54-
rev: v1.5.1
54+
rev: v1.6.0
5555
hooks:
5656
- id: mypy
5757
args:

DIRECTORY.md

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,12 @@
5454
* [Largest Pow Of Two Le Num](bit_manipulation/largest_pow_of_two_le_num.py)
5555
* [Missing Number](bit_manipulation/missing_number.py)
5656
* [Numbers Different Signs](bit_manipulation/numbers_different_signs.py)
57+
* [Power Of 4](bit_manipulation/power_of_4.py)
5758
* [Reverse Bits](bit_manipulation/reverse_bits.py)
5859
* [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py)
5960

6061
## Blockchain
61-
* [Chinese Remainder Theorem](blockchain/chinese_remainder_theorem.py)
6262
* [Diophantine Equation](blockchain/diophantine_equation.py)
63-
* [Modular Division](blockchain/modular_division.py)
6463

6564
## Boolean Algebra
6665
* [And Gate](boolean_algebra/and_gate.py)
@@ -101,11 +100,13 @@
101100
* [Diffie Hellman](ciphers/diffie_hellman.py)
102101
* [Elgamal Key Generator](ciphers/elgamal_key_generator.py)
103102
* [Enigma Machine2](ciphers/enigma_machine2.py)
103+
* [Fractionated Morse Cipher](ciphers/fractionated_morse_cipher.py)
104104
* [Hill Cipher](ciphers/hill_cipher.py)
105105
* [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py)
106106
* [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py)
107107
* [Morse Code](ciphers/morse_code.py)
108108
* [Onepad Cipher](ciphers/onepad_cipher.py)
109+
* [Permutation Cipher](ciphers/permutation_cipher.py)
109110
* [Playfair Cipher](ciphers/playfair_cipher.py)
110111
* [Polybius](ciphers/polybius.py)
111112
* [Porta Cipher](ciphers/porta_cipher.py)
@@ -172,6 +173,7 @@
172173

173174
## Data Structures
174175
* Arrays
176+
* [Equilibrium Index In Array](data_structures/arrays/equilibrium_index_in_array.py)
175177
* [Median Two Array](data_structures/arrays/median_two_array.py)
176178
* [Permutations](data_structures/arrays/permutations.py)
177179
* [Prefix Sum](data_structures/arrays/prefix_sum.py)
@@ -352,6 +354,7 @@
352354
* [Smith Waterman](dynamic_programming/smith_waterman.py)
353355
* [Subset Generation](dynamic_programming/subset_generation.py)
354356
* [Sum Of Subset](dynamic_programming/sum_of_subset.py)
357+
* [Trapped Water](dynamic_programming/trapped_water.py)
355358
* [Tribonacci](dynamic_programming/tribonacci.py)
356359
* [Viterbi](dynamic_programming/viterbi.py)
357360
* [Word Break](dynamic_programming/word_break.py)
@@ -360,6 +363,7 @@
360363
* [Apparent Power](electronics/apparent_power.py)
361364
* [Builtin Voltage](electronics/builtin_voltage.py)
362365
* [Carrier Concentration](electronics/carrier_concentration.py)
366+
* [Charging Capacitor](electronics/charging_capacitor.py)
363367
* [Circular Convolution](electronics/circular_convolution.py)
364368
* [Coulombs Law](electronics/coulombs_law.py)
365369
* [Electric Conductivity](electronics/electric_conductivity.py)
@@ -466,6 +470,8 @@
466470
* [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py)
467471

468472
## Greedy Methods
473+
* [Best Time To Buy And Sell Stock](greedy_methods/best_time_to_buy_and_sell_stock.py)
474+
* [Fractional Cover Problem](greedy_methods/fractional_cover_problem.py)
469475
* [Fractional Knapsack](greedy_methods/fractional_knapsack.py)
470476
* [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py)
471477
* [Gas Station](greedy_methods/gas_station.py)
@@ -524,6 +530,11 @@
524530
* Local Weighted Learning
525531
* [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py)
526532
* [Logistic Regression](machine_learning/logistic_regression.py)
533+
* Loss Functions
534+
* [Binary Cross Entropy](machine_learning/loss_functions/binary_cross_entropy.py)
535+
* [Categorical Cross Entropy](machine_learning/loss_functions/categorical_cross_entropy.py)
536+
* [Huber Loss](machine_learning/loss_functions/huber_loss.py)
537+
* [Mean Squared Error](machine_learning/loss_functions/mean_squared_error.py)
527538
* [Mfcc](machine_learning/mfcc.py)
528539
* [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py)
529540
* [Polynomial Regression](machine_learning/polynomial_regression.py)
@@ -556,15 +567,17 @@
556567
* [Bell Numbers](maths/bell_numbers.py)
557568
* [Binary Exp Mod](maths/binary_exp_mod.py)
558569
* [Binary Exponentiation](maths/binary_exponentiation.py)
559-
* [Binary Exponentiation 3](maths/binary_exponentiation_3.py)
570+
* [Binary Exponentiation 2](maths/binary_exponentiation_2.py)
560571
* [Binary Multiplication](maths/binary_multiplication.py)
561572
* [Binomial Coefficient](maths/binomial_coefficient.py)
562573
* [Binomial Distribution](maths/binomial_distribution.py)
563574
* [Bisection](maths/bisection.py)
564575
* [Carmichael Number](maths/carmichael_number.py)
565576
* [Catalan Number](maths/catalan_number.py)
566577
* [Ceil](maths/ceil.py)
578+
* [Chebyshev Distance](maths/chebyshev_distance.py)
567579
* [Check Polygon](maths/check_polygon.py)
580+
* [Chinese Remainder Theorem](maths/chinese_remainder_theorem.py)
568581
* [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py)
569582
* [Collatz Sequence](maths/collatz_sequence.py)
570583
* [Combinations](maths/combinations.py)
@@ -588,10 +601,10 @@
588601
* [Find Min](maths/find_min.py)
589602
* [Floor](maths/floor.py)
590603
* [Gamma](maths/gamma.py)
591-
* [Gamma Recursive](maths/gamma_recursive.py)
592604
* [Gaussian](maths/gaussian.py)
593605
* [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py)
594606
* [Gcd Of N Numbers](maths/gcd_of_n_numbers.py)
607+
* [Germain Primes](maths/germain_primes.py)
595608
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
596609
* [Greedy Coin Change](maths/greedy_coin_change.py)
597610
* [Hamming Numbers](maths/hamming_numbers.py)
@@ -619,7 +632,9 @@
619632
* [Matrix Exponentiation](maths/matrix_exponentiation.py)
620633
* [Max Sum Sliding Window](maths/max_sum_sliding_window.py)
621634
* [Median Of Two Arrays](maths/median_of_two_arrays.py)
635+
* [Minkowski Distance](maths/minkowski_distance.py)
622636
* [Mobius Function](maths/mobius_function.py)
637+
* [Modular Division](maths/modular_division.py)
623638
* [Modular Exponential](maths/modular_exponential.py)
624639
* [Monte Carlo](maths/monte_carlo.py)
625640
* [Monte Carlo Dice](maths/monte_carlo_dice.py)
@@ -721,11 +736,16 @@
721736
## Neural Network
722737
* [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py)
723738
* Activation Functions
739+
* [Binary Step](neural_network/activation_functions/binary_step.py)
724740
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
725741
* [Leaky Rectified Linear Unit](neural_network/activation_functions/leaky_rectified_linear_unit.py)
742+
* [Mish](neural_network/activation_functions/mish.py)
726743
* [Rectified Linear Unit](neural_network/activation_functions/rectified_linear_unit.py)
727744
* [Scaled Exponential Linear Unit](neural_network/activation_functions/scaled_exponential_linear_unit.py)
728745
* [Sigmoid Linear Unit](neural_network/activation_functions/sigmoid_linear_unit.py)
746+
* [Soboleva Modified Hyperbolic Tangent](neural_network/activation_functions/soboleva_modified_hyperbolic_tangent.py)
747+
* [Softplus](neural_network/activation_functions/softplus.py)
748+
* [Squareplus](neural_network/activation_functions/squareplus.py)
729749
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
730750
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
731751
* [Perceptron](neural_network/perceptron.py)
@@ -748,6 +768,7 @@
748768
* [Linear Congruential Generator](other/linear_congruential_generator.py)
749769
* [Lru Cache](other/lru_cache.py)
750770
* [Magicdiamondpattern](other/magicdiamondpattern.py)
771+
* [Majority Vote Algorithm](other/majority_vote_algorithm.py)
751772
* [Maximum Subsequence](other/maximum_subsequence.py)
752773
* [Nested Brackets](other/nested_brackets.py)
753774
* [Number Container System](other/number_container_system.py)
@@ -778,6 +799,7 @@
778799
* [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)
779800
* [Photoelectric Effect](physics/photoelectric_effect.py)
780801
* [Potential Energy](physics/potential_energy.py)
802+
* [Reynolds Number](physics/reynolds_number.py)
781803
* [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py)
782804
* [Shear Stress](physics/shear_stress.py)
783805
* [Speed Of Sound](physics/speed_of_sound.py)
@@ -1100,6 +1122,7 @@
11001122
* [Interpolation Search](searches/interpolation_search.py)
11011123
* [Jump Search](searches/jump_search.py)
11021124
* [Linear Search](searches/linear_search.py)
1125+
* [Median Of Medians](searches/median_of_medians.py)
11031126
* [Quick Select](searches/quick_select.py)
11041127
* [Sentinel Linear Search](searches/sentinel_linear_search.py)
11051128
* [Simple Binary Search](searches/simple_binary_search.py)
@@ -1196,11 +1219,11 @@
11961219
* [Rabin Karp](strings/rabin_karp.py)
11971220
* [Remove Duplicate](strings/remove_duplicate.py)
11981221
* [Reverse Letters](strings/reverse_letters.py)
1199-
* [Reverse Long Words](strings/reverse_long_words.py)
12001222
* [Reverse Words](strings/reverse_words.py)
12011223
* [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py)
12021224
* [Split](strings/split.py)
12031225
* [String Switch Case](strings/string_switch_case.py)
1226+
* [Strip](strings/strip.py)
12041227
* [Text Justification](strings/text_justification.py)
12051228
* [Top K Frequent Words](strings/top_k_frequent_words.py)
12061229
* [Upper](strings/upper.py)

arithmetic_analysis/gaussian_elimination.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def retroactive_resolution(
3434
x: NDArray[float64] = np.zeros((rows, 1), dtype=float)
3535
for row in reversed(range(rows)):
3636
total = np.dot(coefficients[row, row + 1 :], x[row + 1 :])
37-
x[row, 0] = (vector[row] - total) / coefficients[row, row]
37+
x[row, 0] = (vector[row][0] - total[0]) / coefficients[row, row]
3838

3939
return x
4040

backtracking/word_search.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,7 @@ def word_exists(board: list[list[str]], word: str) -> bool:
9898
False
9999
>>> word_exists([["A"]], "A")
100100
True
101-
>>> word_exists([["A","A","A","A","A","A"],
102-
... ["A","A","A","A","A","A"],
103-
... ["A","A","A","A","A","A"],
104-
... ["A","A","A","A","A","A"],
105-
... ["A","A","A","A","A","B"],
106-
... ["A","A","A","A","B","A"]],
107-
... "AAAAAAAAAAAAABB")
101+
>>> word_exists([["B", "A", "A"], ["A", "A", "A"], ["A", "B", "A"]], "ABB")
108102
False
109103
>>> word_exists([["A"]], 123)
110104
Traceback (most recent call last):

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()

blockchain/diophantine_equation.py

Lines changed: 8 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
from __future__ import annotations
22

3+
from maths.greatest_common_divisor import greatest_common_divisor
4+
35

46
def diophantine(a: int, b: int, c: int) -> tuple[float, float]:
57
"""
68
Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the
79
diophantine equation a*x + b*y = c has a solution (where x and y are integers)
8-
iff gcd(a,b) divides c.
10+
iff greatest_common_divisor(a,b) divides c.
911
1012
GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor )
1113
@@ -22,7 +24,7 @@ def diophantine(a: int, b: int, c: int) -> tuple[float, float]:
2224

2325
assert (
2426
c % greatest_common_divisor(a, b) == 0
25-
) # greatest_common_divisor(a,b) function implemented below
27+
) # greatest_common_divisor(a,b) is in maths directory
2628
(d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below
2729
r = c / d
2830
return (r * x, r * y)
@@ -69,32 +71,6 @@ def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None:
6971
print(x, y)
7072

7173

72-
def greatest_common_divisor(a: int, b: int) -> int:
73-
"""
74-
Euclid's Lemma : d divides a and b, if and only if d divides a-b and b
75-
76-
Euclid's Algorithm
77-
78-
>>> greatest_common_divisor(7,5)
79-
1
80-
81-
Note : In number theory, two integers a and b are said to be relatively prime,
82-
mutually prime, or co-prime if the only positive integer (factor) that
83-
divides both of them is 1 i.e., gcd(a,b) = 1.
84-
85-
>>> greatest_common_divisor(121, 11)
86-
11
87-
88-
"""
89-
if a < b:
90-
a, b = b, a
91-
92-
while a % b != 0:
93-
a, b = b, a % b
94-
95-
return b
96-
97-
9874
def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
9975
"""
10076
Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers
@@ -107,7 +83,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
10783
(1, -2, 3)
10884
10985
"""
110-
assert a >= 0 and b >= 0
86+
assert a >= 0
87+
assert b >= 0
11188

11289
if b == 0:
11390
d, x, y = a, 1, 0
@@ -116,7 +93,8 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
11693
x = q
11794
y = p - q * (a // b)
11895

119-
assert a % d == 0 and b % d == 0
96+
assert a % d == 0
97+
assert b % d == 0
12098
assert d == a * x + b * y
12199

122100
return (d, x, y)

0 commit comments

Comments
 (0)