Skip to content

Commit 996a928

Browse files
authored
Merge branch 'master' into master
2 parents 54fb7a2 + c27e951 commit 996a928

32 files changed

Lines changed: 2921 additions & 316 deletions

‎DIRECTORY.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,8 +262,10 @@
262262

263263
## [Data Structures](data_structures)
264264
* Arrays
265+
* [Dynamic Array](data_structures/arrays/dynamic_array.py)
265266
* [Equilibrium Index In Array](data_structures/arrays/equilibrium_index_in_array.py)
266267
* [Find Triplets With 0 Sum](data_structures/arrays/find_triplets_with_0_sum.py)
268+
* [Gas Station](data_structures/arrays/gas_station.py)
267269
* [Index 2D Array In 1D](data_structures/arrays/index_2d_array_in_1d.py)
268270
* [Kth Largest Element](data_structures/arrays/kth_largest_element.py)
269271
* [Median Two Array](data_structures/arrays/median_two_array.py)
@@ -303,6 +305,7 @@
303305
* [Mirror Binary Tree](data_structures/binary_tree/mirror_binary_tree.py)
304306
* [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py)
305307
* [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py)
308+
* [Persistent Segment Tree](data_structures/binary_tree/persistent_segment_tree.py)
306309
* [Red Black Tree](data_structures/binary_tree/red_black_tree.py)
307310
* [Segment Tree](data_structures/binary_tree/segment_tree.py)
308311
* [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py)
@@ -540,12 +543,15 @@
540543
* [Test Send File](file_transfer/tests/test_send_file.py)
541544

542545
## [Financial](financial)
546+
* [Annuity Due Future Value](financial/annuity_due_future_value.py)
543547
* [Equated Monthly Installments](financial/equated_monthly_installments.py)
544548
* [Expected Shortfall](financial/expected_shortfall.py)
545549
* [Exponential Moving Average](financial/exponential_moving_average.py)
550+
* [Fractional Differentiation](financial/fractional_differentiation.py)
546551
* [Interest](financial/interest.py)
547552
* [Kelly Criterion](financial/kelly_criterion.py)
548553
* [Macaulay Duration](financial/macaulay_duration.py)
554+
* [Ordinary Annuity Future Value](financial/ordinary_annuity_future_value.py)
549555
* [Present Value](financial/present_value.py)
550556
* [Price Plus Tax](financial/price_plus_tax.py)
551557
* [Sharpe Ratio](financial/sharpe_ratio.py)
@@ -629,6 +635,7 @@
629635
* [Dijkstra Binary Grid](graphs/dijkstra_binary_grid.py)
630636
* [Dinic](graphs/dinic.py)
631637
* [Directed And Undirected Weighted Graph](graphs/directed_and_undirected_weighted_graph.py)
638+
* [Edmonds Blossom Algorithm](graphs/edmonds_blossom_algorithm.py)
632639
* [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py)
633640
* [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py)
634641
* [Even Tree](graphs/even_tree.py)
@@ -638,7 +645,9 @@
638645
* [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py)
639646
* [Graph Adjacency List](graphs/graph_adjacency_list.py)
640647
* [Graph Adjacency Matrix](graphs/graph_adjacency_matrix.py)
648+
* [Graph Centrality](graphs/graph_centrality.py)
641649
* [Graph List](graphs/graph_list.py)
650+
* [Graph Peripherality](graphs/graph_peripherality.py)
642651
* [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py)
643652
* [Greedy Best First](graphs/greedy_best_first.py)
644653
* [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py)
@@ -664,13 +673,15 @@
664673
* [Strongly Connected Components](graphs/strongly_connected_components.py)
665674
* [Tarjans Scc](graphs/tarjans_scc.py)
666675
* Tests
676+
* [Test Edmonds Blossom Algorithm](graphs/tests/test_edmonds_blossom_algorithm.py)
667677
* [Test Graphs Floyd Warshall](graphs/tests/test_graphs_floyd_warshall.py)
668678
* [Test Johnson](graphs/tests/test_johnson.py)
669679
* [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py)
670680
* [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py)
671681
* [Travelling Salesman Problem](graphs/travelling_salesman_problem.py)
672682

673683
## [Greedy Methods](greedy_methods)
684+
* [Activity Selection](greedy_methods/activity_selection.py)
674685
* [Best Time To Buy And Sell Stock](greedy_methods/best_time_to_buy_and_sell_stock.py)
675686
* [Fractional Cover Problem](greedy_methods/fractional_cover_problem.py)
676687
* [Fractional Knapsack](greedy_methods/fractional_knapsack.py)
@@ -885,6 +896,7 @@
885896
* [Nevilles Method](maths/numerical_analysis/nevilles_method.py)
886897
* [Newton Forward Interpolation](maths/numerical_analysis/newton_forward_interpolation.py)
887898
* [Newton Raphson](maths/numerical_analysis/newton_raphson.py)
899+
* [Nth Root](maths/numerical_analysis/nth_root.py)
888900
* [Numerical Integration](maths/numerical_analysis/numerical_integration.py)
889901
* [Proper Fractions](maths/numerical_analysis/proper_fractions.py)
890902
* [Runge Kutta](maths/numerical_analysis/runge_kutta.py)
@@ -960,6 +972,7 @@
960972
* [Happy Number](maths/special_numbers/happy_number.py)
961973
* [Harshad Numbers](maths/special_numbers/harshad_numbers.py)
962974
* [Hexagonal Number](maths/special_numbers/hexagonal_number.py)
975+
* [Jacobsthal Number](maths/special_numbers/jacobsthal_number.py)
963976
* [Kaprekar Constant](maths/special_numbers/kaprekar_constant.py)
964977
* [Kaprekar Number](maths/special_numbers/kaprekar_number.py)
965978
* [Krishnamurthy Number](maths/special_numbers/krishnamurthy_number.py)
@@ -1052,6 +1065,7 @@
10521065
* [Nesterov Accelerated Sgd](neural_network/optimizers/nesterov_accelerated_sgd.py)
10531066
* [Perceptron](neural_network/perceptron.py)
10541067
* [Simple Neural Network](neural_network/simple_neural_network.py)
1068+
* [Sliding Window Attention](neural_network/sliding_window_attention.py)
10551069
* [Two Hidden Layers Neural Network](neural_network/two_hidden_layers_neural_network.py)
10561070

10571071
## [Other](other)
@@ -1592,9 +1606,11 @@
15921606
* [Knuth Morris Pratt](strings/knuth_morris_pratt.py)
15931607
* [Largest Smallest Words](strings/largest_smallest_words.py)
15941608
* [Levenshtein Distance](strings/levenshtein_distance.py)
1609+
* [Longest Word In Sentence](strings/longest_word_in_sentence.py)
15951610
* [Lower](strings/lower.py)
15961611
* [Manacher](strings/manacher.py)
15971612
* [Min Cost String Conversion](strings/min_cost_string_conversion.py)
1613+
* [Min Window Substring](strings/min_window_substring.py)
15981614
* [Naive String Search](strings/naive_string_search.py)
15991615
* [Ngram](strings/ngram.py)
16001616
* [Palindrome](strings/palindrome.py)
@@ -1606,6 +1622,7 @@
16061622
* [Reverse Words](strings/reverse_words.py)
16071623
* [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py)
16081624
* [Split](strings/split.py)
1625+
* [String Is Valid Number](strings/string_is_valid_number.py)
16091626
* [String Switch Case](strings/string_switch_case.py)
16101627
* [Strip](strings/strip.py)
16111628
* [Suffix Automaton](strings/suffix_automaton.py)
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
class DynamicArray:
2+
def __init__(self) -> None:
3+
self.size = 0 # Number of elements in the array
4+
self.capacity = 1 # Initial capacity of the array
5+
self.array = [None] * self.capacity # Create an array with initial capacity
6+
7+
def append(self, item: int) -> None:
8+
"""
9+
The function adds an item to the end of the dynamic array.
10+
11+
Runtime : O(1) amortized
12+
Space: O(1) amortized
13+
14+
>>> arr = DynamicArray()
15+
>>> arr.append(1)
16+
>>> arr.append(2)
17+
>>> arr.append(3)
18+
>>> arr.array[:arr.size] # Display only the filled part of the array
19+
[1, 2, 3]
20+
>>> arr.append(4)
21+
>>> arr.array[:arr.size]
22+
[1, 2, 3, 4]
23+
>>> arr.append(5)
24+
>>> arr.array[:arr.size]
25+
[1, 2, 3, 4, 5]
26+
"""
27+
if self.size == self.capacity:
28+
self._resize(2 * self.capacity) # Double the capacity
29+
30+
self.array[self.size] = item
31+
self.size += 1
32+
33+
def _resize(self, new_capacity: int) -> None:
34+
"""
35+
Resizes the array to the new capacity.
36+
37+
Runtime : O(n)
38+
Space: O(n)
39+
40+
>>> arr = DynamicArray()
41+
>>> arr.append(1)
42+
>>> arr.append(2)
43+
>>> arr._resize(10)
44+
>>> arr.capacity
45+
10
46+
>>> arr.array[:arr.size]
47+
[1, 2]
48+
"""
49+
new_array = [None] * new_capacity
50+
for i in range(self.size):
51+
new_array[i] = self.array[i]
52+
self.array = new_array
53+
self.capacity = new_capacity
54+
55+
def get(self, index: int) -> int:
56+
"""
57+
The function returns the item at the specified index.
58+
59+
Runtime : O(1)
60+
Space: O(1)
61+
62+
>>> arr = DynamicArray()
63+
>>> arr.append(1)
64+
>>> arr.append(2)
65+
>>> arr.get(0)
66+
1
67+
>>> arr.get(1)
68+
2
69+
>>> arr.get(2)
70+
Traceback (most recent call last):
71+
...
72+
IndexError: index out of range
73+
>>> arr.get(-1)
74+
Traceback (most recent call last):
75+
...
76+
IndexError: index out of range
77+
"""
78+
if index < 0 or index >= self.size:
79+
raise IndexError("index out of range")
80+
return self.array[index]
81+
82+
def __setitem__(self, index: int, value: int) -> None:
83+
if index < 0 or index >= self.size:
84+
raise IndexError("index out of range")
85+
self.array[index] = value
86+
87+
def __len__(self) -> int:
88+
"""
89+
Returns the number of elements in the dynamic array.
90+
91+
Runtime : O(1)
92+
Space: O(1)
93+
94+
>>> arr = DynamicArray()
95+
>>> arr.append(1)
96+
>>> len(arr)
97+
1
98+
>>> arr.append(2)
99+
>>> len(arr)
100+
2
101+
>>> arr.append(3)
102+
>>> len(arr)
103+
3
104+
"""
105+
return self.size
106+
107+
def __str__(self) -> str:
108+
"""
109+
Returns a string representation of the dynamic array.
110+
111+
>>> arr = DynamicArray()
112+
>>> arr.append(1)
113+
>>> arr.append(2)
114+
>>> arr.append(3)
115+
>>> str(arr)
116+
'[1, 2, 3]'
117+
>>> arr.append(4)
118+
>>> str(arr)
119+
'[1, 2, 3, 4]'
120+
"""
121+
return "[" + ", ".join(str(self.array[i]) for i in range(self.size)) + "]"
122+
123+
124+
if __name__ == "__main__":
125+
import doctest
126+
127+
doctest.testmod()
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from typing import NamedTuple
2+
3+
4+
class GasStation(NamedTuple):
5+
gas: int # Amount of gas available at this gas station
6+
cost: int # Cost of gas required to drive to the next station
7+
8+
9+
def can_complete_circuit(gas_stations: list[GasStation]) -> int:
10+
"""
11+
Finds the starting station index to complete the circuit,
12+
or returns -1 if not possible.
13+
Args:
14+
gas_stations (List[GasStation]): List of gas stations with gas and cost.
15+
Returns:
16+
The index of the starting station, or -1 if no solution exists.
17+
Examples:
18+
>>> GS = GasStation
19+
>>> test_stations = (
20+
... [GS(1, 3), GS(2, 4), GS(3, 5), GS(4, 1), GS(5, 2)],
21+
... [GS(2, 3), GS(3, 4), GS(4, 3)],
22+
... [GS(5, 4), GS(1, 4), GS(2, 1), GS(3, 5), GS(4, 1)]
23+
... )
24+
>>> can_complete_circuit(test_stations[0])
25+
3
26+
>>> can_complete_circuit(test_stations[1])
27+
-1
28+
>>> can_complete_circuit(test_stations[2])
29+
4
30+
"""
31+
total_gas = sum(station.gas - station.cost for station in gas_stations)
32+
current_gas: int = 0
33+
start_station = 0
34+
for i, gas_station in enumerate(gas_stations):
35+
needed_gas = gas_station.gas - gas_station.cost
36+
total_gas += needed_gas
37+
current_gas += needed_gas
38+
if current_gas < 0:
39+
start_station = i + 1
40+
current_gas = 0
41+
if total_gas < 0:
42+
return -1
43+
return start_station
44+
45+
46+
# Example usage with doctests
47+
if __name__ == "__main__":
48+
import doctest
49+
50+
doctest.testmod()

0 commit comments

Comments
 (0)