Calculate the span values for a given list of stock prices. Args: price: List of stock prices. Returns: List of span values. >>> calculate_span([10, 4, 5, 90, 120, 80]) [1, 1, 2, 4, 5, 1] >>> calculate_span([100, 50, 60, 70, 80, 90]) [1, 1, 2, 3, 4, 5]
(price: list[int])
| 9 | |
| 10 | |
| 11 | def calculate_span(price: list[int]) -> list[int]: |
| 12 | """ |
| 13 | Calculate the span values for a given list of stock prices. |
| 14 | Args: |
| 15 | price: List of stock prices. |
| 16 | Returns: |
| 17 | List of span values. |
| 18 | |
| 19 | >>> calculate_span([10, 4, 5, 90, 120, 80]) |
| 20 | [1, 1, 2, 4, 5, 1] |
| 21 | >>> calculate_span([100, 50, 60, 70, 80, 90]) |
| 22 | [1, 1, 2, 3, 4, 5] |
| 23 | >>> calculate_span([5, 4, 3, 2, 1]) |
| 24 | [1, 1, 1, 1, 1] |
| 25 | >>> calculate_span([1, 2, 3, 4, 5]) |
| 26 | [1, 2, 3, 4, 5] |
| 27 | >>> calculate_span([10, 20, 30, 40, 50]) |
| 28 | [1, 2, 3, 4, 5] |
| 29 | >>> calculate_span([100, 80, 60, 70, 60, 75, 85]) |
| 30 | [1, 1, 1, 2, 1, 4, 6] |
| 31 | """ |
| 32 | n = len(price) |
| 33 | s = [0] * n |
| 34 | # Create a stack and push index of fist element to it |
| 35 | st = [] |
| 36 | st.append(0) |
| 37 | |
| 38 | # Span value of first element is always 1 |
| 39 | s[0] = 1 |
| 40 | |
| 41 | # Calculate span values for rest of the elements |
| 42 | for i in range(1, n): |
| 43 | # Pop elements from stack while stack is not |
| 44 | # empty and top of stack is smaller than price[i] |
| 45 | while len(st) > 0 and price[st[-1]] <= price[i]: |
| 46 | st.pop() |
| 47 | |
| 48 | # If stack becomes empty, then price[i] is greater |
| 49 | # than all elements on left of it, i.e. price[0], |
| 50 | # price[1], ..price[i-1]. Else the price[i] is |
| 51 | # greater than elements after top of stack |
| 52 | s[i] = i + 1 if len(st) <= 0 else (i - st[-1]) |
| 53 | |
| 54 | # Push this element to stack |
| 55 | st.append(i) |
| 56 | |
| 57 | return s |
| 58 | |
| 59 | |
| 60 | # A utility function to print elements of array |
no test coverage detected