Skip to content

Commit 01e2cd4

Browse files
Update stock_span_problem.py
1 parent b756caa commit 01e2cd4

File tree

1 file changed

+42
-17
lines changed

1 file changed

+42
-17
lines changed

data_structures/stacks/stock_span_problem.py

Lines changed: 42 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,46 +8,71 @@
88
"""
99

1010

11-
def calculation_span(price: list[float]) -> list[float]:
11+
def calculate_span(price: list[int]) -> list[int]:
1212
"""
1313
Calculate the span values for a given list of stock prices.
1414
Args:
15-
price (list): List of stock prices.
15+
price: List of stock prices.
1616
Returns:
17+
List of span values.
18+
1719
>>> price = [10, 4, 5, 90, 120, 80]
18-
>>> calculation_span(price)
20+
>>> calculate_span(price)
1921
[1.0, 1.0, 2.0, 4.0, 5.0, 1.0]
2022
>>> price = [100, 50, 60, 70, 80, 90]
21-
>>> calculation_span(price)
23+
>>> calculate_span(price)
2224
[1.0, 1.0, 2.0, 3.0, 4.0, 5.0]
2325
>>> price = [5, 4, 3, 2, 1]
24-
>>> calculation_span(price)
26+
>>> calculate_span(price)
2527
[1.0, 1.0, 1.0, 1.0, 1.0]
2628
>>> price = [1, 2, 3, 4, 5]
27-
>>> calculation_span(price)
29+
>>> calculate_span(price)
2830
[1.0, 2.0, 3.0, 4.0, 5.0]
2931
>>> price = [10, 20, 30, 40, 50]
30-
>>> calculation_span(price)
32+
>>> calculate_span(price)
3133
[1.0, 2.0, 3.0, 4.0, 5.0]
3234
>>> calculation_span(price=[100, 80, 60, 70, 60, 75, 85])
3335
[1.0, 1.0, 1.0, 2.0, 1.0, 4.0, 6.0]
3436
"""
3537
n = len(price)
36-
st = [0]
37-
s = [1.0]
38+
s = [0] * n
39+
# Create a stack and push index of fist element to it
40+
st = []
41+
st.append(0)
42+
43+
# Span value of first element is always 1
44+
s[0] = 1
45+
46+
# Calculate span values for rest of the elements
3847
for i in range(1, n):
39-
while st and price[st[-1]] <= price[i]:
48+
# Pop elements from stack while stack is not
49+
# empty and top of stack is smaller than price[i]
50+
while len(st) > 0 and price[st[0]] <= price[i]:
4051
st.pop()
41-
s.append(float(i - st[-1] if st else i + 1))
52+
53+
# If stack becomes empty, then price[i] is greater
54+
# than all elements on left of it, i.e. price[0],
55+
# price[1], ..price[i-1]. Else the price[i] is
56+
# greater than elements after top of stack
57+
s[i] = i + 1 if len(st) <= 0 else (i - st[0])
58+
59+
# Push this element to stack
4260
st.append(i)
61+
4362
return s
4463

4564

46-
price = [10.0, 4.0, 5.0, 90.0, 120.0, 80.0]
47-
S = calculation_span(price)
48-
print(S)
65+
# A utility function to print elements of array
66+
def print_array(arr, n):
67+
for i in range(n):
68+
print(arr[i], end=" ")
69+
70+
71+
# Driver program to test above function
72+
price = [10, 4, 5, 90, 120, 80]
4973

50-
if __name__ == "__main__":
51-
import doctest
74+
# Calculate the span values
75+
S = calculate_span(price)
5276

53-
doctest.testmod()
77+
# Print the calculated span values
78+
print_array(S, len(price))

0 commit comments

Comments
 (0)