Skip to content

Commit 2c9d524

Browse files
Added test cases and doctest
1 parent d23bcf5 commit 2c9d524

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

Diff for: other/lru_cache_pythonic.py

+37-1
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,40 @@ def put(self, key:Hashable, value:Any):
4040
if self.remaining > 0: self.remaining -= 1
4141
# To pop the least recently used item from the dictionary
4242
else: self.pop(next(iter(self)))
43-
self[key] = value
43+
self[key] = value
44+
45+
def main():
46+
'''Example test case with LRU_Cache of size 2'''
47+
cache = LRUCache(2) # Creates an LRU cache with size 2
48+
cache.put(1,1) # cache = {1:1}
49+
cache.put(2,2) # cache = {1:1, 2:2}
50+
try:
51+
print(cache.get(1)) # Prints 1
52+
except KeyError:
53+
print("Key not found in cache")
54+
cache.put(3,3) # cache = {1:1, 3:3} key=2 is evicted because it wasn't used recently
55+
try:
56+
print(cache.get(2))
57+
except KeyError:
58+
print("Key=2 not found in cache") # Prints key not found
59+
cache.put(4,4) # cache = {4:4, 3:3} key=1 is evicted because it wasn't used recently
60+
try:
61+
print(cache.get(1))
62+
except KeyError:
63+
print("Key=1 not found in cache") # Prints key not found
64+
try:
65+
print(cache.get(3)) # Prints value 3
66+
except KeyError:
67+
print("Key not found in cache")
68+
69+
try:
70+
print(cache.get(4)) # Prints value 4
71+
except KeyError:
72+
print("Key not found in cache")
73+
74+
import doctest
75+
doctest.testmod()
76+
77+
if __name__ == '__main__':
78+
main()
79+

0 commit comments

Comments
 (0)