Skip to content

[Mypy] fix other/least_recently_used #5814

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

Merged
merged 18 commits into from
Nov 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
run: |
python -m pip install --upgrade pip setuptools six wheel
python -m pip install mypy pytest-cov -r requirements.txt
- run: mypy . # See `mypy.ini` for configuration settings.
- run: mypy --ignore-missing-imports --install-types --non-interactive .
- name: Run tests
run: pytest --doctest-modules --ignore=project_euler/ --ignore=scripts/validate_solutions.py --cov-report=term-missing:skip-covered --cov=. .
- if: ${{ success() }}
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ jobs:
~/.cache/pip
key: ${{ runner.os }}-pre-commit-${{ hashFiles('.pre-commit-config.yaml') }}
- uses: actions/setup-python@v2
with:
python-version: 3.9
- uses: psf/[email protected]
- name: Install pre-commit
run: |
Expand Down
23 changes: 15 additions & 8 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,26 @@ repos:
data_structures/heap/binomial_heap.py
)$
- id: requirements-txt-fixer

- repo: https://github.com/psf/black
rev: 21.4b0
hooks:
- id: black

- repo: https://github.com/PyCQA/isort
rev: 5.8.0
hooks:
- id: isort
args:
- --profile=black

- repo: https://github.com/asottile/pyupgrade
rev: v2.29.0
hooks:
- id: pyupgrade
args:
- --py39-plus

- repo: https://gitlab.com/pycqa/flake8
rev: 3.9.1
hooks:
Expand All @@ -36,27 +40,30 @@ repos:
- --ignore=E203,W503
- --max-complexity=25
- --max-line-length=88
# FIXME: fix mypy errors and then uncomment this
# - repo: https://github.com/pre-commit/mirrors-mypy
# rev: v0.782
# hooks:
# - id: mypy
# args:
# - --ignore-missing-imports

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.910
hooks:
- id: mypy
args:
- --ignore-missing-imports
- --install-types # See mirrors-mypy README.md
- --non-interactive

- repo: https://github.com/codespell-project/codespell
rev: v2.0.0
hooks:
- id: codespell
args:
- --ignore-words-list=ans,crate,fo,followings,hist,iff,mater,secant,som,tim
- --skip="./.*,./strings/dictionary.txt,./strings/words.txt,./project_euler/problem_022/p022_names.txt"
- --quiet-level=2
exclude: |
(?x)^(
strings/dictionary.txt |
strings/words.txt |
project_euler/problem_022/p022_names.txt
)$

- repo: local
hooks:
- id: validate-filenames
Expand Down
5 changes: 0 additions & 5 deletions mypy.ini

This file was deleted.

70 changes: 50 additions & 20 deletions other/least_recently_used.py
Original file line number Diff line number Diff line change
@@ -1,62 +1,92 @@
from __future__ import annotations

import sys
from collections import deque
from typing import Generic, TypeVar

T = TypeVar("T")


class LRUCache(Generic[T]):
"""
Page Replacement Algorithm, Least Recently Used (LRU) Caching.

>>> lru_cache: LRUCache[str | int] = LRUCache(4)
>>> lru_cache.refer("A")
>>> lru_cache.refer(2)
>>> lru_cache.refer(3)

>>> lru_cache
LRUCache(4) => [3, 2, 'A']

>>> lru_cache.refer("A")
>>> lru_cache
LRUCache(4) => ['A', 3, 2]

class LRUCache:
"""Page Replacement Algorithm, Least Recently Used (LRU) Caching."""
>>> lru_cache.refer(4)
>>> lru_cache.refer(5)
>>> lru_cache
LRUCache(4) => [5, 4, 'A', 3]

dq_store = object() # Cache store of keys
key_reference_map = object() # References of the keys in cache
"""

dq_store: deque[T] # Cache store of keys
key_reference: set[T] # References of the keys in cache
_MAX_CAPACITY: int = 10 # Maximum capacity of cache

def __init__(self, n: int):
def __init__(self, n: int) -> None:
"""Creates an empty store and map for the keys.
The LRUCache is set the size n.
"""
self.dq_store = deque()
self.key_reference_map = set()
self.key_reference = set()
if not n:
LRUCache._MAX_CAPACITY = sys.maxsize
elif n < 0:
raise ValueError("n should be an integer greater than 0.")
else:
LRUCache._MAX_CAPACITY = n

def refer(self, x):
def refer(self, x: T) -> None:
"""
Looks for a page in the cache store and adds reference to the set.
Remove the least recently used key if the store is full.
Update store to reflect recent access.
"""
if x not in self.key_reference_map:
if x not in self.key_reference:
if len(self.dq_store) == LRUCache._MAX_CAPACITY:
last_element = self.dq_store.pop()
self.key_reference_map.remove(last_element)
self.key_reference.remove(last_element)
else:
index_remove = 0
for idx, key in enumerate(self.dq_store):
if key == x:
index_remove = idx
break
self.dq_store.remove(index_remove)
self.dq_store.remove(x)

self.dq_store.appendleft(x)
self.key_reference_map.add(x)
self.key_reference.add(x)

def display(self):
def display(self) -> None:
"""
Prints all the elements in the store.
"""
for k in self.dq_store:
print(k)

def __repr__(self) -> str:
return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}"


if __name__ == "__main__":
lru_cache = LRUCache(4)
lru_cache.refer(1)
import doctest

doctest.testmod()

lru_cache: LRUCache[str | int] = LRUCache(4)
lru_cache.refer("A")
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer(1)
lru_cache.refer("A")
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()

print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,4 @@ sympy
tensorflow
texttable
tweepy
types-requests
xgboost