[mypy] Fix type annotations in data_structures/stacks/next_greater_element.py (#5763)

* Fix type annotations in next_greater_element.py

* Refactor next_greater_element.py
This commit is contained in:
Dylan Buchi 2021-11-05 16:45:37 -03:00 committed by GitHub
parent 1a43c92c77
commit e7381b513b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,8 +1,10 @@
from __future__ import annotations
arr = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0]
expect = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1]
def next_greatest_element_slow(arr: list) -> list:
def next_greatest_element_slow(arr: list[float]) -> list[float]:
"""
Get the Next Greatest Element (NGE) for all elements in a list.
Maximum element present after the current one which is also greater than the
@ -10,10 +12,13 @@ def next_greatest_element_slow(arr: list) -> list:
>>> next_greatest_element_slow(arr) == expect
True
"""
result = []
for i in range(0, len(arr), 1):
next = -1
for j in range(i + 1, len(arr), 1):
arr_size = len(arr)
for i in range(arr_size):
next: float = -1
for j in range(i + 1, arr_size):
if arr[i] < arr[j]:
next = arr[j]
break
@ -21,7 +26,7 @@ def next_greatest_element_slow(arr: list) -> list:
return result
def next_greatest_element_fast(arr: list) -> list:
def next_greatest_element_fast(arr: list[float]) -> list[float]:
"""
Like next_greatest_element_slow() but changes the loops to use
enumerate() instead of range(len()) for the outer loop and
@ -31,7 +36,7 @@ def next_greatest_element_fast(arr: list) -> list:
"""
result = []
for i, outer in enumerate(arr):
next = -1
next: float = -1
for inner in arr[i + 1 :]:
if outer < inner:
next = inner
@ -40,7 +45,7 @@ def next_greatest_element_fast(arr: list) -> list:
return result
def next_greatest_element(arr: list) -> list:
def next_greatest_element(arr: list[float]) -> list[float]:
"""
Get the Next Greatest Element (NGE) for all elements in a list.
Maximum element present after the current one which is also greater than the
@ -53,21 +58,19 @@ def next_greatest_element(arr: list) -> list:
>>> next_greatest_element(arr) == expect
True
"""
stack = []
result = [-1] * len(arr)
arr_size = len(arr)
stack: list[float] = []
result: list[float] = [-1] * arr_size
for index in reversed(range(len(arr))):
if len(stack):
for index in reversed(range(arr_size)):
if stack:
while stack[-1] <= arr[index]:
stack.pop()
if len(stack) == 0:
if not stack:
break
if len(stack) != 0:
if stack:
result[index] = stack[-1]
stack.append(arr[index])
return result