Skip to content

Commit 75a94d2

Browse files
committed
Merge branch 'master' of github.com:tianyizheng02/Python
2 parents 7a762ea + 8bf3b06 commit 75a94d2

Some content is hidden

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

41 files changed

+1789
-223
lines changed

Diff for: .pre-commit-config.yaml

+5-5
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@ repos:
1616
- id: auto-walrus
1717

1818
- repo: https://github.com/charliermarsh/ruff-pre-commit
19-
rev: v0.0.259
19+
rev: v0.0.267
2020
hooks:
2121
- id: ruff
2222

2323
- repo: https://github.com/psf/black
24-
rev: 23.1.0
24+
rev: 23.3.0
2525
hooks:
2626
- id: black
2727

@@ -33,7 +33,7 @@ repos:
3333
- tomli
3434

3535
- repo: https://github.com/tox-dev/pyproject-fmt
36-
rev: "0.9.2"
36+
rev: "0.11.2"
3737
hooks:
3838
- id: pyproject-fmt
3939

@@ -46,12 +46,12 @@ repos:
4646
pass_filenames: false
4747

4848
- repo: https://github.com/abravalheri/validate-pyproject
49-
rev: v0.12.1
49+
rev: v0.12.2
5050
hooks:
5151
- id: validate-pyproject
5252

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

Diff for: DIRECTORY.md

+22-1
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@
195195
* [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py)
196196
* [Disjoint Set](data_structures/disjoint_set/disjoint_set.py)
197197
* Hashing
198+
* [Bloom Filter](data_structures/hashing/bloom_filter.py)
198199
* [Double Hash](data_structures/hashing/double_hash.py)
199200
* [Hash Map](data_structures/hashing/hash_map.py)
200201
* [Hash Table](data_structures/hashing/hash_table.py)
@@ -232,6 +233,7 @@
232233
* [Double Ended Queue](data_structures/queue/double_ended_queue.py)
233234
* [Linked Queue](data_structures/queue/linked_queue.py)
234235
* [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py)
236+
* [Queue By Two Stacks](data_structures/queue/queue_by_two_stacks.py)
235237
* [Queue On List](data_structures/queue/queue_on_list.py)
236238
* [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py)
237239
* Stacks
@@ -292,7 +294,6 @@
292294
* [Mergesort](divide_and_conquer/mergesort.py)
293295
* [Peak](divide_and_conquer/peak.py)
294296
* [Power](divide_and_conquer/power.py)
295-
* [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py)
296297

297298
## Dynamic Programming
298299
* [Abbreviation](dynamic_programming/abbreviation.py)
@@ -309,6 +310,7 @@
309310
* [Floyd Warshall](dynamic_programming/floyd_warshall.py)
310311
* [Integer Partition](dynamic_programming/integer_partition.py)
311312
* [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py)
313+
* [K Means Clustering Tensorflow](dynamic_programming/k_means_clustering_tensorflow.py)
312314
* [Knapsack](dynamic_programming/knapsack.py)
313315
* [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py)
314316
* [Longest Common Substring](dynamic_programming/longest_common_substring.py)
@@ -324,6 +326,7 @@
324326
* [Minimum Coin Change](dynamic_programming/minimum_coin_change.py)
325327
* [Minimum Cost Path](dynamic_programming/minimum_cost_path.py)
326328
* [Minimum Partition](dynamic_programming/minimum_partition.py)
329+
* [Minimum Size Subarray Sum](dynamic_programming/minimum_size_subarray_sum.py)
327330
* [Minimum Squares To Represent A Number](dynamic_programming/minimum_squares_to_represent_a_number.py)
328331
* [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py)
329332
* [Minimum Tickets Cost](dynamic_programming/minimum_tickets_cost.py)
@@ -336,6 +339,7 @@
336339
* [Word Break](dynamic_programming/word_break.py)
337340

338341
## Electronics
342+
* [Apparent Power](electronics/apparent_power.py)
339343
* [Builtin Voltage](electronics/builtin_voltage.py)
340344
* [Carrier Concentration](electronics/carrier_concentration.py)
341345
* [Circular Convolution](electronics/circular_convolution.py)
@@ -345,6 +349,7 @@
345349
* [Electrical Impedance](electronics/electrical_impedance.py)
346350
* [Ind Reactance](electronics/ind_reactance.py)
347351
* [Ohms Law](electronics/ohms_law.py)
352+
* [Real And Reactive Power](electronics/real_and_reactive_power.py)
348353
* [Resistor Equivalence](electronics/resistor_equivalence.py)
349354
* [Resonant Frequency](electronics/resonant_frequency.py)
350355

@@ -357,6 +362,7 @@
357362
## Financial
358363
* [Equated Monthly Installments](financial/equated_monthly_installments.py)
359364
* [Interest](financial/interest.py)
365+
* [Present Value](financial/present_value.py)
360366
* [Price Plus Tax](financial/price_plus_tax.py)
361367

362368
## Fractals
@@ -442,6 +448,7 @@
442448
## Greedy Methods
443449
* [Fractional Knapsack](greedy_methods/fractional_knapsack.py)
444450
* [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py)
451+
* [Minimum Waiting Time](greedy_methods/minimum_waiting_time.py)
445452
* [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py)
446453

447454
## Hashes
@@ -480,6 +487,7 @@
480487
* [Astar](machine_learning/astar.py)
481488
* [Data Transformations](machine_learning/data_transformations.py)
482489
* [Decision Tree](machine_learning/decision_tree.py)
490+
* [Dimensionality Reduction](machine_learning/dimensionality_reduction.py)
483491
* Forecasting
484492
* [Run](machine_learning/forecasting/run.py)
485493
* [Gradient Descent](machine_learning/gradient_descent.py)
@@ -601,6 +609,7 @@
601609
* [Perfect Number](maths/perfect_number.py)
602610
* [Perfect Square](maths/perfect_square.py)
603611
* [Persistence](maths/persistence.py)
612+
* [Pi Generator](maths/pi_generator.py)
604613
* [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py)
605614
* [Points Are Collinear 3D](maths/points_are_collinear_3d.py)
606615
* [Pollard Rho](maths/pollard_rho.py)
@@ -622,6 +631,7 @@
622631
* [Radians](maths/radians.py)
623632
* [Radix2 Fft](maths/radix2_fft.py)
624633
* [Relu](maths/relu.py)
634+
* [Remove Digit](maths/remove_digit.py)
625635
* [Runge Kutta](maths/runge_kutta.py)
626636
* [Segmented Sieve](maths/segmented_sieve.py)
627637
* Series
@@ -647,6 +657,7 @@
647657
* [Sum Of Harmonic Series](maths/sum_of_harmonic_series.py)
648658
* [Sumset](maths/sumset.py)
649659
* [Sylvester Sequence](maths/sylvester_sequence.py)
660+
* [Tanh](maths/tanh.py)
650661
* [Test Prime Check](maths/test_prime_check.py)
651662
* [Trapezoidal Rule](maths/trapezoidal_rule.py)
652663
* [Triplet Sum](maths/triplet_sum.py)
@@ -683,8 +694,11 @@
683694

684695
## Neural Network
685696
* [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py)
697+
* Activation Functions
698+
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
686699
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
687700
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
701+
* [Input Data](neural_network/input_data.py)
688702
* [Perceptron](neural_network/perceptron.py)
689703
* [Simple Neural Network](neural_network/simple_neural_network.py)
690704

@@ -704,6 +718,7 @@
704718
* [Lru Cache](other/lru_cache.py)
705719
* [Magicdiamondpattern](other/magicdiamondpattern.py)
706720
* [Maximum Subarray](other/maximum_subarray.py)
721+
* [Maximum Subsequence](other/maximum_subsequence.py)
707722
* [Nested Brackets](other/nested_brackets.py)
708723
* [Password](other/password.py)
709724
* [Quine](other/quine.py)
@@ -920,6 +935,8 @@
920935
* [Sol1](project_euler/problem_077/sol1.py)
921936
* Problem 078
922937
* [Sol1](project_euler/problem_078/sol1.py)
938+
* Problem 079
939+
* [Sol1](project_euler/problem_079/sol1.py)
923940
* Problem 080
924941
* [Sol1](project_euler/problem_080/sol1.py)
925942
* Problem 081
@@ -1031,6 +1048,7 @@
10311048
* [Q Fourier Transform](quantum/q_fourier_transform.py)
10321049
* [Q Full Adder](quantum/q_full_adder.py)
10331050
* [Quantum Entanglement](quantum/quantum_entanglement.py)
1051+
* [Quantum Random](quantum/quantum_random.py)
10341052
* [Quantum Teleportation](quantum/quantum_teleportation.py)
10351053
* [Ripple Adder Classic](quantum/ripple_adder_classic.py)
10361054
* [Single Qubit Measure](quantum/single_qubit_measure.py)
@@ -1064,6 +1082,7 @@
10641082

10651083
## Sorts
10661084
* [Bead Sort](sorts/bead_sort.py)
1085+
* [Binary Insertion Sort](sorts/binary_insertion_sort.py)
10671086
* [Bitonic Sort](sorts/bitonic_sort.py)
10681087
* [Bogo Sort](sorts/bogo_sort.py)
10691088
* [Bubble Sort](sorts/bubble_sort.py)
@@ -1154,7 +1173,9 @@
11541173
* [Reverse Words](strings/reverse_words.py)
11551174
* [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py)
11561175
* [Split](strings/split.py)
1176+
* [String Switch Case](strings/string_switch_case.py)
11571177
* [Text Justification](strings/text_justification.py)
1178+
* [Top K Frequent Words](strings/top_k_frequent_words.py)
11581179
* [Upper](strings/upper.py)
11591180
* [Wave](strings/wave.py)
11601181
* [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py)

Diff for: boolean_algebra/and_gate.py

+2
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ def test_and_gate() -> None:
4343

4444

4545
if __name__ == "__main__":
46+
test_and_gate()
47+
print(and_gate(1, 0))
4648
print(and_gate(0, 0))
4749
print(and_gate(0, 1))
4850
print(and_gate(1, 1))

Diff for: cellular_automata/game_of_life.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
from matplotlib import pyplot as plt
3535
from matplotlib.colors import ListedColormap
3636

37-
usage_doc = "Usage of script: script_nama <size_of_canvas:int>"
37+
usage_doc = "Usage of script: script_name <size_of_canvas:int>"
3838

3939
choice = [0] * 100 + [1] * 10
4040
random.shuffle(choice)

Diff for: ciphers/rsa_cipher.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,11 @@ def encrypt_and_write_to_file(
7676
key_size, n, e = read_key_file(key_filename)
7777
if key_size < block_size * 8:
7878
sys.exit(
79-
"ERROR: Block size is %s bits and key size is %s bits. The RSA cipher "
79+
"ERROR: Block size is {} bits and key size is {} bits. The RSA cipher "
8080
"requires the block size to be equal to or greater than the key size. "
81-
"Either decrease the block size or use different keys."
82-
% (block_size * 8, key_size)
81+
"Either decrease the block size or use different keys.".format(
82+
block_size * 8, key_size
83+
)
8384
)
8485

8586
encrypted_blocks = [str(i) for i in encrypt_message(message, (n, e), block_size)]
@@ -101,10 +102,11 @@ def read_from_file_and_decrypt(message_filename: str, key_filename: str) -> str:
101102

102103
if key_size < block_size * 8:
103104
sys.exit(
104-
"ERROR: Block size is %s bits and key size is %s bits. The RSA cipher "
105+
"ERROR: Block size is {} bits and key size is {} bits. The RSA cipher "
105106
"requires the block size to be equal to or greater than the key size. "
106-
"Did you specify the correct key file and encrypted file?"
107-
% (block_size * 8, key_size)
107+
"Did you specify the correct key file and encrypted file?".format(
108+
block_size * 8, key_size
109+
)
108110
)
109111

110112
encrypted_blocks = []

Diff for: conversions/prefix_conversions_string.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def add_si_prefix(value: float) -> str:
9696
for name_prefix, value_prefix in prefixes.items():
9797
numerical_part = value / (10**value_prefix)
9898
if numerical_part > 1:
99-
return f"{str(numerical_part)} {name_prefix}"
99+
return f"{numerical_part!s} {name_prefix}"
100100
return str(value)
101101

102102

@@ -111,7 +111,7 @@ def add_binary_prefix(value: float) -> str:
111111
for prefix in BinaryUnit:
112112
numerical_part = value / (2**prefix.value)
113113
if numerical_part > 1:
114-
return f"{str(numerical_part)} {prefix.name}"
114+
return f"{numerical_part!s} {prefix.name}"
115115
return str(value)
116116

117117

Diff for: conversions/rgb_hsv_conversion.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,8 @@ def rgb_to_hsv(red: int, green: int, blue: int) -> list[float]:
121121
float_red = red / 255
122122
float_green = green / 255
123123
float_blue = blue / 255
124-
value = max(max(float_red, float_green), float_blue)
125-
chroma = value - min(min(float_red, float_green), float_blue)
124+
value = max(float_red, float_green, float_blue)
125+
chroma = value - min(float_red, float_green, float_blue)
126126
saturation = 0 if value == 0 else chroma / value
127127

128128
if chroma == 0:

Diff for: data_structures/hashing/bloom_filter.py

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
"""
2+
See https://en.wikipedia.org/wiki/Bloom_filter
3+
4+
The use of this data structure is to test membership in a set.
5+
Compared to Python's built-in set() it is more space-efficient.
6+
In the following example, only 8 bits of memory will be used:
7+
>>> bloom = Bloom(size=8)
8+
9+
Initially, the filter contains all zeros:
10+
>>> bloom.bitstring
11+
'00000000'
12+
13+
When an element is added, two bits are set to 1
14+
since there are 2 hash functions in this implementation:
15+
>>> "Titanic" in bloom
16+
False
17+
>>> bloom.add("Titanic")
18+
>>> bloom.bitstring
19+
'01100000'
20+
>>> "Titanic" in bloom
21+
True
22+
23+
However, sometimes only one bit is added
24+
because both hash functions return the same value
25+
>>> bloom.add("Avatar")
26+
>>> "Avatar" in bloom
27+
True
28+
>>> bloom.format_hash("Avatar")
29+
'00000100'
30+
>>> bloom.bitstring
31+
'01100100'
32+
33+
Not added elements should return False ...
34+
>>> not_present_films = ("The Godfather", "Interstellar", "Parasite", "Pulp Fiction")
35+
>>> {
36+
... film: bloom.format_hash(film) for film in not_present_films
37+
... } # doctest: +NORMALIZE_WHITESPACE
38+
{'The Godfather': '00000101',
39+
'Interstellar': '00000011',
40+
'Parasite': '00010010',
41+
'Pulp Fiction': '10000100'}
42+
>>> any(film in bloom for film in not_present_films)
43+
False
44+
45+
but sometimes there are false positives:
46+
>>> "Ratatouille" in bloom
47+
True
48+
>>> bloom.format_hash("Ratatouille")
49+
'01100000'
50+
51+
The probability increases with the number of elements added.
52+
The probability decreases with the number of bits in the bitarray.
53+
>>> bloom.estimated_error_rate
54+
0.140625
55+
>>> bloom.add("The Godfather")
56+
>>> bloom.estimated_error_rate
57+
0.25
58+
>>> bloom.bitstring
59+
'01100101'
60+
"""
61+
from hashlib import md5, sha256
62+
63+
HASH_FUNCTIONS = (sha256, md5)
64+
65+
66+
class Bloom:
67+
def __init__(self, size: int = 8) -> None:
68+
self.bitarray = 0b0
69+
self.size = size
70+
71+
def add(self, value: str) -> None:
72+
h = self.hash_(value)
73+
self.bitarray |= h
74+
75+
def exists(self, value: str) -> bool:
76+
h = self.hash_(value)
77+
return (h & self.bitarray) == h
78+
79+
def __contains__(self, other: str) -> bool:
80+
return self.exists(other)
81+
82+
def format_bin(self, bitarray: int) -> str:
83+
res = bin(bitarray)[2:]
84+
return res.zfill(self.size)
85+
86+
@property
87+
def bitstring(self) -> str:
88+
return self.format_bin(self.bitarray)
89+
90+
def hash_(self, value: str) -> int:
91+
res = 0b0
92+
for func in HASH_FUNCTIONS:
93+
position = (
94+
int.from_bytes(func(value.encode()).digest(), "little") % self.size
95+
)
96+
res |= 2**position
97+
return res
98+
99+
def format_hash(self, value: str) -> str:
100+
return self.format_bin(self.hash_(value))
101+
102+
@property
103+
def estimated_error_rate(self) -> float:
104+
n_ones = bin(self.bitarray).count("1")
105+
return (n_ones / self.size) ** len(HASH_FUNCTIONS)

0 commit comments

Comments
 (0)