Skip to content

Commit

Permalink
Refactor DP
Browse files Browse the repository at this point in the history
  • Loading branch information
everysoftware committed Jan 24, 2025
1 parent 0ff4f80 commit b68ed2e
Show file tree
Hide file tree
Showing 52 changed files with 569 additions and 958 deletions.
1 change: 1 addition & 0 deletions src/a_intro/line_reflection.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# O(n)
def is_reflected(points: list[list[int]]) -> bool:
min_x, max_x = float("inf"), float("-inf")
points_set = set()
Expand Down
1 change: 1 addition & 0 deletions src/a_intro/max_power.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# O(n)
def max_power(s: str) -> int:
mx = 1
count = 1
Expand Down
1 change: 1 addition & 0 deletions src/a_intro/summary_ranges.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# O(n)
def summary_ranges(nums: list[int]) -> list[str]:
ranges: list[list[int]] = []
for num in nums:
Expand Down
67 changes: 10 additions & 57 deletions src/b_base_ds/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
|-----------|--------------------------------------------------------------|
| Сложность | Легкая |
| Источник | https://stepik.org/lesson/41234/step/1?unit=19818 |
| LeetCode | https://leetcode.com/problems/valid-parentheses/description/ |
| Похожие | https://leetcode.com/problems/valid-parentheses/description/ |

Вы разрабатываете текстовый редактор для программистов и хотите реализовать проверку корректности
расстановки скобок. В коде могут встречаться скобки []{}(). В случае, если скобки расставлены неправильно,
Expand Down Expand Up @@ -166,7 +166,7 @@ Success
| Сложность | Сложная |
| Источник | https://stepik.org/lesson/41234/step/4?unit=19818 |
| LeetCode | https://leetcode.com/problems/max-stack/description/ |
| Похожая | https://leetcode.com/problems/maximum-frequency-stack/description/ |
| Похожие | https://leetcode.com/problems/maximum-frequency-stack/description/ |

Стек — абстрактная структура данных, поддерживающая операции push и pop. Несложно реализовать стек так,
чтобы обе эти операции работали за константное время. В данной задаче ваша цель — расширить интерфейс стека так,
Expand Down Expand Up @@ -207,62 +207,15 @@ max
| Поле | Значение |
|-----------|-------------------------------------------------------------------|
| Сложность | Сложная |
| Источник | https://stepik.org/lesson/41234/step/5?unit=19818 |
| LeetCode | https://leetcode.com/problems/sliding-window-maximum/description/ |
| Источник | https://leetcode.com/problems/sliding-window-maximum/description/ |
| Stepik | https://stepik.org/lesson/41234/step/5?unit=19818 |
| Похожая | https://leetcode.com/problems/sliding-window-median/description/ |

Найти максимум в каждом окне размера m данного массива чисел A[1...n].

Формат входа. Первая строка входа содержит число n, вторая — массив A[1...n],
третья — число m.

Формат выхода. Максимум подмассива A[i...i + m − 1] для всех 1 ≤ i ≤ n − m + 1.

Пример.

Вход:

```
8
2 7 3 1 5 2 6 2
4
```

Выход:

```
7 7 5 6 6
```

## F. Калькулятор

| Поле | Значение |
|-----------|-----------------------------------------------------------------------------|
| Сложность | Средняя |
| Источник | https://contest.yandex.ru/contest/31463/problems/?nc=cwKgF8vK |
| Похожие | https://leetcode.com/problems/evaluate-reverse-polish-notation/description/ |

Реализовать алгоритм разбора арифметического выражения. Допустимые операции в выражении: "+", "-", "*", "/",
числовые литералы, круглые скобки для задания приоритетности.

Формат ввода.
В качестве входа для алгоритма задана единственная строка - записанное арифметическое выражение.

Формат вывода.
Результатом работы алгоритма является вычисленное значение входного выражения.
Помимо результата необходимо вывести запись исходного выражения в постфиксной записи (обратной польской записи).

Пример.

Ввод:

```
(1+2)*4+3
```

Вывод:

```
1 2 + 4 * 3 +
15
```
| Поле | Значение |
|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------|
| Сложность | Сложная |
| Источник | https://leetcode.com/problems/basic-calculator/description/ |
| Яндекс Контесты | https://contest.yandex.ru/contest/31463/problems/?nc=cwKgF8vK |
| Похожие | https://leetcode.com/problems/basic-calculator-ii/description/<br/>https://leetcode.com/problems/evaluate-reverse-polish-notation/description/ |
27 changes: 0 additions & 27 deletions src/b_base_ds/__init__.py
Original file line number Diff line number Diff line change
@@ -1,27 +0,0 @@
from src.tba_trees.tree_height import tree_height_naive, tree_height_stack
from .bank_queue import average_waiting_time
from .brackets import brackets
from .calculator import (
get_postfix_notation,
split_by_tokens,
evaluate_postfix,
calculator,
)
from .max_stack import MaxStack
from .net_packets import net_packets
from .sliding_window import sliding_window_naive, sliding_window_deque

__all__ = [
"brackets",
"net_packets",
"tree_height_naive",
"tree_height_stack",
"sliding_window_naive",
"sliding_window_deque",
"average_waiting_time",
"get_postfix_notation",
"split_by_tokens",
"evaluate_postfix",
"MaxStack",
"calculator",
]
3 changes: 1 addition & 2 deletions src/b_base_ds/brackets.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,4 @@ def brackets(s: str) -> int | None:
stack.pop()
else:
return i + 1
result = (stack.pop() + 1) if stack else None
return result
return (stack.pop() + 1) if stack else None
81 changes: 41 additions & 40 deletions src/b_base_ds/calculator.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# O(n)
def calculator(expression: str) -> tuple[str, float]:
def calculator(expression: str) -> float:
postfix_notation = get_postfix_notation(expression)
result = evaluate_postfix(postfix_notation)
return postfix_notation, result
return result


priority = {
Expand All @@ -24,52 +24,36 @@ def calculator(expression: str) -> tuple[str, float]:
}


# O(n)
def split_by_tokens(expression: str) -> list[str]:
tokens = []
token = ""
for c in expression:
if c.isdigit() or c in ".":
token += c
elif not c.isspace():
if token:
tokens.append(token)
token = ""
tokens.append(c)
if token:
tokens.append(token)
return tokens


# O(n)
def get_postfix_notation(expression: str) -> str:
notation: list[str] = []
stack: list[str] = []
operations: list[str] = []
tokens = split_by_tokens(expression)
for token in tokens:
if token in priority:
for i, token in enumerate(tokens):
# Число.
if token not in priority:
notation.append(token)
# Операция.
else:
# Открытие скобочного выражения.
if not stack or token == "(":
stack.append(token)
if token == "(":
operations.append(token)
# Закрытие скобочного выражения.
elif token == ")":
top = stack.pop()
while top != "(":
notation.append(top)
top = stack.pop()
# При очередной операции добавляем в результат, все операции из стека с большим или равным приоритетом.
elif priority[token] <= priority[stack[-1]]:
top = stack.pop()
notation.append(top)
while stack and priority[top] != priority[token]:
top = stack.pop()
notation.append(top)
stack.append(token)
while operations and operations[-1] != "(":
notation.append(operations.pop())
operations.pop()
# Операция.
else:
stack.append(token)
else:
notation.append(token)
notation += stack
# Унарный плюс или минус.
if token in "+-" and (i == 0 or tokens[i - 1] in priority or tokens[i - 1] == "("):
notation.append("0")
# Перенос операций с большим или равным приоритетом из стека в выходную строку.
while operations and priority[operations[-1]] >= priority[token]:
notation.append(operations.pop())
operations.append(token)
# Перенос оставшихся операций из стека в выходную строку.
notation += operations[::-1]
return " ".join(notation)


Expand All @@ -85,3 +69,20 @@ def evaluate_postfix(expression: str) -> float:
else:
stack.append(float(token))
return stack[0] if stack else 0.0


# O(n)
def split_by_tokens(expression: str) -> list[str]:
tokens = []
token = ""
for c in expression:
if c.isdigit() or c == ".":
token += c
elif not c.isspace():
if token:
tokens.append(token)
token = ""
tokens.append(c)
if token:
tokens.append(token)
return tokens
1 change: 1 addition & 0 deletions src/c_search/matrix_search.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# O(n + m)
def ladder_search(a: list[list[int]], target: int) -> tuple[int, int]:
"""
1. Начинаем с правого верхнего угла.
Expand Down
23 changes: 12 additions & 11 deletions src/c_search/search_range.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
# O(log(N))
# O(log n)
def search_range(a: list[int], target: int) -> list[int]:
low, high = lower_bound(a, target), upper_bound(a, target) - 1
if low < 0 or low >= len(a) or a[low] != target:
low = -1
if high < 0 or high >= len(a) or a[high] != target:
high = -1
return [low, high]


# O(log n)
def lower_bound(
a: list[int],
target: int,
Expand All @@ -20,7 +30,7 @@ def lower_bound(
return low


# O(log(N))
# O(log n)
def upper_bound(
a: list[int],
target: int,
Expand All @@ -39,12 +49,3 @@ def upper_bound(
else:
low = m + 1
return low


def search_range(a: list[int], target: int) -> list[int]:
low, high = lower_bound(a, target), upper_bound(a, target) - 1
if low < 0 or low >= len(a) or a[low] != target:
low = -1
if high < 0 or high >= len(a) or a[high] != target:
high = -1
return [low, high]
1 change: 1 addition & 0 deletions src/c_search/sqrt.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# O(log x)
def sqrt(x: int) -> int:
if x < 2:
return x
Expand Down
1 change: 1 addition & 0 deletions src/g_prefix_sums/product_except_self.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# O(n)
def product_except_self(nums: list[int]) -> list[int]:
n = len(nums)
res = [1] * (n + 1)
Expand Down
1 change: 1 addition & 0 deletions src/h_number_theory/array_gcd.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# O(n)
def find_gcd(nums: list[int]) -> int:
return gcd_euclid(min(nums), max(nums))

Expand Down
Loading

0 comments on commit b68ed2e

Please sign in to comment.