Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding doctests in stock_span_problem.py #10540

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 35 additions & 33 deletions data_structures/stacks/stock_span_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,44 +8,46 @@
"""


def calculation_span(price, s):
def calculation_span(price: list[float]) -> list[float]:
"""
Calculate the span values for a given list of stock prices.
Args:
price (list): List of stock prices.
Returns:
>>> price = [10, 4, 5, 90, 120, 80]
>>> calculation_span(price)
[1.0, 1.0, 2.0, 4.0, 5.0, 1.0]
>>> price = [100, 50, 60, 70, 80, 90]
>>> calculation_span(price)
[1.0, 1.0, 2.0, 3.0, 4.0, 5.0]
>>> price = [5, 4, 3, 2, 1]
>>> calculation_span(price)
[1.0, 1.0, 1.0, 1.0, 1.0]
>>> price = [1, 2, 3, 4, 5]
>>> calculation_span(price)
[1.0, 2.0, 3.0, 4.0, 5.0]
>>> price = [10, 20, 30, 40, 50]
>>> calculation_span(price)
[1.0, 2.0, 3.0, 4.0, 5.0]
>>> calculation_span(price=[100, 80, 60, 70, 60, 75, 85])
[1.0, 1.0, 1.0, 2.0, 1.0, 4.0, 6.0]
"""
n = len(price)
# Create a stack and push index of fist element to it
st = []
st.append(0)

# Span value of first element is always 1
s[0] = 1

# Calculate span values for rest of the elements
st = [0]
s = [1.0]
for i in range(1, n):
# Pop elements from stack while stack is not
# empty and top of stack is smaller than price[i]
while len(st) > 0 and price[st[0]] <= price[i]:
while st and price[st[-1]] <= price[i]:
st.pop()

# If stack becomes empty, then price[i] is greater
# than all elements on left of it, i.e. price[0],
# price[1], ..price[i-1]. Else the price[i] is
# greater than elements after top of stack
s[i] = i + 1 if len(st) <= 0 else (i - st[0])

# Push this element to stack
s.append(float(i - st[-1] if st else i + 1))
st.append(i)
return s


# A utility function to print elements of array
def print_array(arr, n):
for i in range(n):
print(arr[i], end=" ")


# Driver program to test above function
price = [10, 4, 5, 90, 120, 80]
S = [0 for i in range(len(price) + 1)]
price = [10.0, 4.0, 5.0, 90.0, 120.0, 80.0]
S = calculation_span(price)
print(S)

# Fill the span values in array S[]
calculation_span(price, S)
if __name__ == "__main__":
import doctest

# Print the calculated span values
print_array(S, len(price))
doctest.testmod()