-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
Pythonic implementation of LRU Cache #4630
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
cclauss
merged 10 commits into
TheAlgorithms:master
from
yatharthmathur:pythonic-implementations
Jul 30, 2023
Merged
Changes from 8 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
d23bcf5
Added a more pythonic implementation of LRU_Cache.[#4628]
yatharthmathur 2c9d524
Added test cases and doctest
yatharthmathur e5b6af1
Fixed doc tests
yatharthmathur fc53f3b
Added more tests in doctests and fixed return types fixes [#4628]
yatharthmathur b237fb3
better doctests
yatharthmathur b931537
added doctests to main()
yatharthmathur 59fec2a
Added dutch_national_flag.py in sorts. fixing [#4636]
yatharthmathur 73e9c44
Delete dutch_national_flag.py
yatharthmathur 34b70da
Update lru_cache_pythonic.py
cclauss 4f7c0c0
Remove pontification
cclauss 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
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 |
---|---|---|
@@ -0,0 +1,107 @@ | ||
from typing import Any, Hashable | ||
|
||
''' | ||
The following implementation of LRU Cache is one of the most elegant pythonic implementations. | ||
It only uses the in-built python dictionary (https://docs.python.org/3/library/stdtypes.html#typesmapping). This works because | ||
the Python dictionary maintains the order of insertion of keys and ensures O(1) operations on insert, delete and access. | ||
''' | ||
class LRUCache(dict): | ||
def __init__(self, capacity : int)->None: | ||
''' | ||
Initialize an LRU Cache with given capacity. | ||
capacity : int -> the capacity of the LRU Cache | ||
>>> cache = LRUCache(2) | ||
>>> cache | ||
{} | ||
''' | ||
self.remaining:int = capacity | ||
|
||
def get(self, key:Hashable)->Any: | ||
yatharthmathur marked this conversation as resolved.
Show resolved
Hide resolved
|
||
''' | ||
This method gets the value associated with the key. | ||
key : Hashable -> a hashable object that is mapped to a value inside of the LRU cache. | ||
returns -> value : Any -> any object that is stored as a value inside of the LRU cache. | ||
|
||
>>> cache = LRUCache(2) | ||
>>> cache.put(1,1) | ||
>>> cache.get(1) | ||
1 | ||
>>> cache.get(2) | ||
Traceback (most recent call last): | ||
... | ||
KeyError: '2 not found.' | ||
''' | ||
if key not in self: | ||
raise KeyError(f"{key} not found.") | ||
val = self.pop(key) # Pop the key-value and re-insert to maintain the order | ||
self[key] = val | ||
return val | ||
|
||
|
||
def put(self, key:Hashable, value:Any)->None: | ||
yatharthmathur marked this conversation as resolved.
Show resolved
Hide resolved
|
||
''' | ||
This method puts the value associated with the key provided inside of the LRU cache. | ||
key : Hashable -> a hashable object that is mapped to a value inside of the LRU cache. | ||
value: Any -> any object that is to be associated with the key inside of the LRU cache. | ||
>>> cache = LRUCache(2) | ||
>>> cache.put(3,3) | ||
>>> cache | ||
{3: 3} | ||
>>> cache.put(2,2) | ||
>>> cache | ||
{3: 3, 2: 2} | ||
''' | ||
# To pop the last value inside of the LRU cache | ||
if key in self: | ||
self.pop(key) | ||
self[key] = value | ||
return | ||
|
||
if self.remaining > 0: self.remaining -= 1 | ||
# To pop the least recently used item from the dictionary | ||
else: self.pop(next(iter(self))) | ||
self[key] = value | ||
|
||
def main()->None: | ||
yatharthmathur marked this conversation as resolved.
Show resolved
Hide resolved
yatharthmathur marked this conversation as resolved.
Show resolved
Hide resolved
|
||
'''Example test case with LRU_Cache of size 2 | ||
>>> main() | ||
1 | ||
Key=2 not found in cache | ||
Key=1 not found in cache | ||
3 | ||
4 | ||
''' | ||
cache = LRUCache(2) # Creates an LRU cache with size 2 | ||
cache.put(1,1) # cache = {1:1} | ||
cache.put(2,2) # cache = {1:1, 2:2} | ||
try: | ||
print(cache.get(1)) # Prints 1 | ||
except KeyError: | ||
print("Key not found in cache") | ||
cache.put(3,3) # cache = {1:1, 3:3} key=2 is evicted because it wasn't used recently | ||
try: | ||
print(cache.get(2)) | ||
except KeyError: | ||
print("Key=2 not found in cache") # Prints key not found | ||
cache.put(4,4) # cache = {4:4, 3:3} key=1 is evicted because it wasn't used recently | ||
try: | ||
print(cache.get(1)) | ||
except KeyError: | ||
print("Key=1 not found in cache") # Prints key not found | ||
try: | ||
print(cache.get(3)) # Prints value 3 | ||
except KeyError: | ||
print("Key not found in cache") | ||
|
||
try: | ||
print(cache.get(4)) # Prints value 4 | ||
except KeyError: | ||
print("Key not found in cache") | ||
|
||
|
||
|
||
if __name__ == '__main__': | ||
import doctest | ||
doctest.testmod() | ||
main() | ||
|
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.
Uh oh!
There was an error while loading. Please reload this page.