diff --git a/DIRECTORY.md b/DIRECTORY.md index 41a2d2e9af03..2df9d56e99b7 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -725,6 +725,7 @@ * [Secant Method](maths/numerical_analysis/secant_method.py) * [Simpson Rule](maths/numerical_analysis/simpson_rule.py) * [Square Root](maths/numerical_analysis/square_root.py) + * [Weierstrass Method](maths/numerical_analysis/weierstrass_method.py) * [Odd Sieve](maths/odd_sieve.py) * [Perfect Cube](maths/perfect_cube.py) * [Perfect Number](maths/perfect_number.py) diff --git a/data_structures/stacks/stock_span_problem.py b/data_structures/stacks/stock_span_problem.py index 5efe58d25798..74c2636784e2 100644 --- a/data_structures/stacks/stock_span_problem.py +++ b/data_structures/stacks/stock_span_problem.py @@ -8,8 +8,29 @@ """ -def calculation_span(price, s): +def calculate_span(price: list[int]) -> list[int]: + """ + 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] + >>> calculate_span([5, 4, 3, 2, 1]) + [1, 1, 1, 1, 1] + >>> calculate_span([1, 2, 3, 4, 5]) + [1, 2, 3, 4, 5] + >>> calculate_span([10, 20, 30, 40, 50]) + [1, 2, 3, 4, 5] + >>> calculate_span([100, 80, 60, 70, 60, 75, 85]) + [1, 1, 1, 2, 1, 4, 6] + """ n = len(price) + s = [0] * n # Create a stack and push index of fist element to it st = [] st.append(0) @@ -21,18 +42,20 @@ def calculation_span(price, s): 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 len(st) > 0 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]) + s[i] = i + 1 if len(st) <= 0 else (i - st[-1]) # Push this element to stack st.append(i) + return s + # A utility function to print elements of array def print_array(arr, n): @@ -42,10 +65,9 @@ def print_array(arr, n): # Driver program to test above function price = [10, 4, 5, 90, 120, 80] -S = [0 for i in range(len(price) + 1)] -# Fill the span values in array S[] -calculation_span(price, S) +# Calculate the span values +S = calculate_span(price) # Print the calculated span values print_array(S, len(price))