-
Notifications
You must be signed in to change notification settings - Fork 0
Эффективность по памяти #5
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
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
998e065
Реализованы эффективнее по памяти все
Cinnamonness d808b57
Добавлено README для эффективности по памяти
Cinnamonness 63891d3
Отредактировано README
Cinnamonness 89f0cf9
Редактировано после PR
Cinnamonness df6e54a
Отредактирован тест для списка после PR
Cinnamonness File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,44 +1,81 @@ | ||
| from copy import deepcopy | ||
| from typing import Optional, Any | ||
|
|
||
|
|
||
| class NodeState: | ||
| """Класс, представляющий состояние узла.""" | ||
| def __init__(self, data: Optional['NodeState'] = None): | ||
| self.data = data | ||
| self.next_node: Optional['NodeState'] = None | ||
|
|
||
|
|
||
| class Node: | ||
| """Класс узла для хранения состояния в B-дереве.""" | ||
| def __init__(self, state: NodeState | None) -> None: | ||
| """ | ||
| Инициализирует узел с заданным состоянием. | ||
|
|
||
| :param state: Состояние узла. | ||
| """ | ||
| self.state: NodeState | None = state | ||
| self.children: dict[int, Node] = {} | ||
|
|
||
|
|
||
| class BasePersistent: | ||
| """Базовый класс для персистентных стркутур данных. | ||
|
|
||
| Каждая персистентная структура будет хранить в себе историю изменений в виде словаря с ключами | ||
| версиями и значениями - состояниями. Также персистентная структура будет хранить номер ткущей | ||
| и номер последней версии. | ||
| """ | ||
| def __init__(self, initial_state=None) -> None: | ||
| """Инициализирует персистентную структуру данных. | ||
| """Базовый класс для персистентных структур данных с использованием B-дерева.""" | ||
|
|
||
| def __init__(self, initial_state: Optional[NodeState] = None) -> None: | ||
| """ | ||
| Инициализирует персистентную структуру данных. | ||
|
|
||
| :param initial_state: Начальное состояние персистентной структуры данных. | ||
| """ | ||
| self._history = {0: initial_state} | ||
| self._current_state = 0 | ||
| self._last_state = 0 | ||
| self.root: Node = Node(initial_state) | ||
| self._current_version: int = 0 | ||
| self._last_version: int = 0 | ||
| self._version_map: dict[int, Node] = {0: self.root} | ||
|
|
||
| def get_version(self, version): | ||
| """Возвращает состояние персистентной структуры данных на указанной версии. | ||
| def get_version(self, version: int) -> dict[Any, Any]: | ||
| """ | ||
| Возвращает состояние персистентной структуры данных на указанной версии. | ||
|
|
||
| :param version: Номер версии. | ||
| :return: Состояние персистентной структуры данных на указанной версии. | ||
| :raises ValueError: Если указанная версия не существует. | ||
| """ | ||
| if version < 0 or version >= len(self._history): | ||
| if version not in self._version_map: | ||
| raise ValueError(f'Version "{version}" does not exist') | ||
| return self._history[version] | ||
| return self._version_map[version].state | ||
|
|
||
| def update_version(self, version): | ||
| """Обновляет текущую версию персистентной структуры данных до указанной. | ||
| def set_version(self, version: int) -> None: | ||
| """ | ||
| Обновляет текущую версию персистентной структуры данных до указанной. | ||
|
|
||
| :param version: Номер версии. | ||
| :raises ValueError: Если указанная версия не существует. | ||
| """ | ||
| if version < 0 or version >= len(self._history): | ||
| if version not in self._version_map: | ||
| raise ValueError(f'Version "{version}" does not exist') | ||
| self._current_state = version | ||
| self._current_version = version | ||
| self.root = self._version_map[version] | ||
|
|
||
| def _create_new_state(self) -> None: | ||
| """Создает новую версию.""" | ||
| self._last_state += 1 | ||
| self._history[self._last_state] = deepcopy(self._history[self._current_state]) | ||
| self._current_state = self._last_state | ||
| """ | ||
| Создает новую версию персистентной структуры данных с | ||
| минимальным дублированием данных. | ||
|
|
||
| Этот метод копирует текущее состояние структуры данных и создает | ||
| новую версию, добавляя ее в карту версий. | ||
| Дублирование данных минимизируется путем использования глубокого | ||
| копирования состояния узла. | ||
|
|
||
| :raises ValueError: Если текущая версия не существует в карте версий. | ||
| """ | ||
| self._last_version += 1 | ||
| parent_node = self._version_map[self._current_version] | ||
| new_state = deepcopy(parent_node.state) | ||
| new_node = Node(new_state) | ||
| parent_node.children[self._last_version] = new_node | ||
| self._version_map[self._last_version] = new_node | ||
| self._current_version = self._last_version | ||
| self.root = new_node | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
С питона 3.10 вместо data: Optional['NodeState'] = None можно писать:
data: NodeState | None = None