From d23bcf563aecd112b8defb0962b68106aae24116 Mon Sep 17 00:00:00 2001 From: yatharthmathur Date: Wed, 18 Aug 2021 23:49:58 +0530 Subject: [PATCH 01/10] Added a more pythonic implementation of LRU_Cache.[#4628] --- other/lru_cache_pythonic.py | 43 +++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 other/lru_cache_pythonic.py diff --git a/other/lru_cache_pythonic.py b/other/lru_cache_pythonic.py new file mode 100644 index 000000000000..b8ed71c2635f --- /dev/null +++ b/other/lru_cache_pythonic.py @@ -0,0 +1,43 @@ +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. 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): + ''' + Initialize an LRU Cache with given capacity. + capacity : int -> the capacity of the LRU Cache + ''' + def __init__(self, capacity : int): + self.remaining:int = capacity + + ''' + 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. + ''' + def get(self, key:Hashable)->Any: + 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 + + ''' + 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. + ''' + def put(self, key:Hashable, value:Any): + # 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 \ No newline at end of file From 2c9d524a0159aa0d40183fd5432d25d10fed27e3 Mon Sep 17 00:00:00 2001 From: yatharthmathur Date: Thu, 19 Aug 2021 10:31:39 +0530 Subject: [PATCH 02/10] Added test cases and doctest --- other/lru_cache_pythonic.py | 38 ++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/other/lru_cache_pythonic.py b/other/lru_cache_pythonic.py index b8ed71c2635f..ce0963068cc2 100644 --- a/other/lru_cache_pythonic.py +++ b/other/lru_cache_pythonic.py @@ -40,4 +40,40 @@ def put(self, key:Hashable, value:Any): 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 \ No newline at end of file + self[key] = value + +def main(): + '''Example test case with LRU_Cache of size 2''' + 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") + + import doctest + doctest.testmod() + +if __name__ == '__main__': + main() + From e5b6af164ae404c8ace075d90e71af0d0e9d4ece Mon Sep 17 00:00:00 2001 From: yatharthmathur Date: Thu, 19 Aug 2021 10:42:12 +0530 Subject: [PATCH 03/10] Fixed doc tests --- other/lru_cache_pythonic.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/other/lru_cache_pythonic.py b/other/lru_cache_pythonic.py index ce0963068cc2..3c4f22929b37 100644 --- a/other/lru_cache_pythonic.py +++ b/other/lru_cache_pythonic.py @@ -2,7 +2,7 @@ ''' The following implementation of LRU Cache is one of the most elegant pythonic implementations. -It only uses the in-built python dictionary. This works because +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): @@ -17,6 +17,13 @@ def __init__(self, capacity : int): 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) + KeyError: '2 not found.' ''' def get(self, key:Hashable)->Any: if key not in self: From fc53f3b6247ec1fda1c64b71001767645652ff78 Mon Sep 17 00:00:00 2001 From: yatharthmathur Date: Thu, 19 Aug 2021 10:50:10 +0530 Subject: [PATCH 04/10] Added more tests in doctests and fixed return types fixes [#4628] --- other/lru_cache_pythonic.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/other/lru_cache_pythonic.py b/other/lru_cache_pythonic.py index 3c4f22929b37..e24afd33d4fa 100644 --- a/other/lru_cache_pythonic.py +++ b/other/lru_cache_pythonic.py @@ -10,7 +10,7 @@ class LRUCache(dict): Initialize an LRU Cache with given capacity. capacity : int -> the capacity of the LRU Cache ''' - def __init__(self, capacity : int): + def __init__(self, capacity : int)->None: self.remaining:int = capacity ''' @@ -36,8 +36,15 @@ def get(self, key:Hashable)->Any: 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} ''' - def put(self, key:Hashable, value:Any): + def put(self, key:Hashable, value:Any)->None: # To pop the last value inside of the LRU cache if key in self: self.pop(key) @@ -49,7 +56,7 @@ def put(self, key:Hashable, value:Any): else: self.pop(next(iter(self))) self[key] = value -def main(): +def main()->None: '''Example test case with LRU_Cache of size 2''' cache = LRUCache(2) # Creates an LRU cache with size 2 cache.put(1,1) # cache = {1:1} From b237fb3d0bfdf3b609cda185032a95814d42f447 Mon Sep 17 00:00:00 2001 From: yatharthmathur Date: Thu, 19 Aug 2021 11:05:25 +0530 Subject: [PATCH 05/10] better doctests --- other/lru_cache_pythonic.py | 67 ++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/other/lru_cache_pythonic.py b/other/lru_cache_pythonic.py index e24afd33d4fa..7b9ae3a5c454 100644 --- a/other/lru_cache_pythonic.py +++ b/other/lru_cache_pythonic.py @@ -6,45 +6,51 @@ the Python dictionary maintains the order of insertion of keys and ensures O(1) operations on insert, delete and access. ''' class LRUCache(dict): - ''' - Initialize an LRU Cache with given capacity. - capacity : int -> the capacity of the LRU Cache - ''' 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 - ''' - 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) - KeyError: '2 not found.' - ''' def get(self, key:Hashable)->Any: + ''' + 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 - ''' - 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} - ''' + def put(self, key:Hashable, value:Any)->None: + ''' + 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) @@ -85,9 +91,10 @@ def main()->None: except KeyError: print("Key not found in cache") - import doctest - doctest.testmod() + if __name__ == '__main__': + import doctest + doctest.testmod() main() From b93153728116f2edc87dfa5e5de94f66e6e3c858 Mon Sep 17 00:00:00 2001 From: yatharthmathur Date: Thu, 19 Aug 2021 11:12:27 +0530 Subject: [PATCH 06/10] added doctests to main() --- other/lru_cache_pythonic.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/other/lru_cache_pythonic.py b/other/lru_cache_pythonic.py index 7b9ae3a5c454..0b791d394173 100644 --- a/other/lru_cache_pythonic.py +++ b/other/lru_cache_pythonic.py @@ -63,7 +63,14 @@ def put(self, key:Hashable, value:Any)->None: self[key] = value def main()->None: - '''Example test case with LRU_Cache of size 2''' + '''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} From 59fec2a84a8a64edf0a97f880c27e7036a8a7d70 Mon Sep 17 00:00:00 2001 From: yatharthmathur Date: Thu, 19 Aug 2021 19:51:41 +0530 Subject: [PATCH 07/10] Added dutch_national_flag.py in sorts. fixing [#4636] --- sorts/dutch_national_flag.py | 89 ++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 sorts/dutch_national_flag.py diff --git a/sorts/dutch_national_flag.py b/sorts/dutch_national_flag.py new file mode 100644 index 000000000000..c6305d73a939 --- /dev/null +++ b/sorts/dutch_national_flag.py @@ -0,0 +1,89 @@ +from typing import List, Any, Tuple +import random + +# These constants stores the relative order of the 3 'colors' 0, 1 and 2. +# They can be changed as per the requirement of the user. +# The colors need not be represented by integers, they can also be other comparable or incomparable objects. +RED = 0 # In this case this is the first color of the flag. +WHITE = 1 # This is the second color of the flag. +BLUE = 2 # This is the third color of the flag. +COLORS = (RED, WHITE, BLUE) +""" +The Dutch-National-Flag problem is a problem designed by Edsger Dijkstra. This is called so because the flag of Netherlands +or Dutch flag is composed of three colors and the sequence of numbers it seeks to sort is composed of 3 unique repeated values. +These values can be in any order (0,1,2) in our examples but can be made to be anything by assigning the value to RED, WHITE and BLUE +in that order. + +The objective is to sort these n numbers composed of 3 unique repeated values in the most optimal way, that is O(n) (better than the normal +list.sort() method in Python which has the complexity of O(n)). Another way to solve it is by using Counting Sort but that requires 2 +passes and depending on the size of array could be much more expensive than DNF algorithm (twice as much). + +The idea is to maintain 4 regions inside of the sequence provided (marked by l, mid and r index). +for a sequence of size n: +Region 1 : sequence[0...l-1] should be colored RED +Region 2 : sequence[l...mid-1] should be colored WHITE +Region 3 : sequence[mid...r] is an unknown color that we must process +Region 4 : sequence[r...n] should be colored BLUE + +More can be read here : https://en.wikipedia.org/wiki/Dutch_national_flag_problem + +""" +def dutch_national_flag(sequence : List, colors:Tuple[Any]=COLORS) -> None: + """ + This method sorts the sequence of 3 colors given in the order in COLORS constant tuple. This method assumes (0<1<2) + but the order can be anything. + Inputs : + colors : Tuple[Any] -> a relative ordered tuple of objects that correspond to RED, WHITE and BLUE colors of the flag (in that order). + sequence : List[any] -> a sequence of length n with values a[0], a[1], a[2] ... a[n-2], a[n-1] where a[i] in COLORS + input example : [0, 0, 2, 2, 2, 1, 1, 2, 2, 1] + output example : [0, 0, 1, 1, 1, 2, 2, 2, 2, 2] + Sorts the array in place in a single pass. O(n) time complexity and O(1) space complexity + >>> from collections import Counter + >>> arr1 = [random.choice(COLORS) for _ in range(100)] + >>> arr2 = arr1.copy() + >>> counter = Counter(arr1) + >>> arr1 = [COLORS[0] for _ in range(counter[COLORS[0]])]+[COLORS[1] for _ in range(counter[COLORS[1]])]+\ +[COLORS[2] for _ in range(counter[COLORS[2]])] + >>> dutch_national_flag(arr2) + >>> arr1 == arr2 + True + """ + COLORS = colors + if sequence is None: return + if len(sequence) <= 1: return + l = 0 + mid = 0 + r = len(sequence)-1 + while mid <= r: + if sequence[mid] == COLORS[0]: + sequence[l], sequence[mid] = sequence[mid], sequence[l] + l+=1 + mid+=1 + continue + + if sequence[mid] == COLORS[1]: + mid+=1 + continue + + if sequence[mid] == COLORS[2]: + sequence[r], sequence[mid] = sequence[mid], sequence[r] + r-=1 + continue + + raise ValueError(f"Invalid value {sequence[mid]} inside of sequence. The elements inside the sequence must \ + be in {COLORS} tuple.") + + return + + +def main()->None: + """ + Main method to run doctests + >>> pass + """ + import doctest + doctest.testmod() + + +if __name__ == "__main__": + main() \ No newline at end of file From 73e9c44a08f594bf4e01f53efd1f2cde96071f41 Mon Sep 17 00:00:00 2001 From: Yatharth Mathur <31852880+yatharthmathur@users.noreply.github.com> Date: Thu, 19 Aug 2021 19:55:33 +0530 Subject: [PATCH 08/10] Delete dutch_national_flag.py incorrect commit --- sorts/dutch_national_flag.py | 89 ------------------------------------ 1 file changed, 89 deletions(-) delete mode 100644 sorts/dutch_national_flag.py diff --git a/sorts/dutch_national_flag.py b/sorts/dutch_national_flag.py deleted file mode 100644 index c6305d73a939..000000000000 --- a/sorts/dutch_national_flag.py +++ /dev/null @@ -1,89 +0,0 @@ -from typing import List, Any, Tuple -import random - -# These constants stores the relative order of the 3 'colors' 0, 1 and 2. -# They can be changed as per the requirement of the user. -# The colors need not be represented by integers, they can also be other comparable or incomparable objects. -RED = 0 # In this case this is the first color of the flag. -WHITE = 1 # This is the second color of the flag. -BLUE = 2 # This is the third color of the flag. -COLORS = (RED, WHITE, BLUE) -""" -The Dutch-National-Flag problem is a problem designed by Edsger Dijkstra. This is called so because the flag of Netherlands -or Dutch flag is composed of three colors and the sequence of numbers it seeks to sort is composed of 3 unique repeated values. -These values can be in any order (0,1,2) in our examples but can be made to be anything by assigning the value to RED, WHITE and BLUE -in that order. - -The objective is to sort these n numbers composed of 3 unique repeated values in the most optimal way, that is O(n) (better than the normal -list.sort() method in Python which has the complexity of O(n)). Another way to solve it is by using Counting Sort but that requires 2 -passes and depending on the size of array could be much more expensive than DNF algorithm (twice as much). - -The idea is to maintain 4 regions inside of the sequence provided (marked by l, mid and r index). -for a sequence of size n: -Region 1 : sequence[0...l-1] should be colored RED -Region 2 : sequence[l...mid-1] should be colored WHITE -Region 3 : sequence[mid...r] is an unknown color that we must process -Region 4 : sequence[r...n] should be colored BLUE - -More can be read here : https://en.wikipedia.org/wiki/Dutch_national_flag_problem - -""" -def dutch_national_flag(sequence : List, colors:Tuple[Any]=COLORS) -> None: - """ - This method sorts the sequence of 3 colors given in the order in COLORS constant tuple. This method assumes (0<1<2) - but the order can be anything. - Inputs : - colors : Tuple[Any] -> a relative ordered tuple of objects that correspond to RED, WHITE and BLUE colors of the flag (in that order). - sequence : List[any] -> a sequence of length n with values a[0], a[1], a[2] ... a[n-2], a[n-1] where a[i] in COLORS - input example : [0, 0, 2, 2, 2, 1, 1, 2, 2, 1] - output example : [0, 0, 1, 1, 1, 2, 2, 2, 2, 2] - Sorts the array in place in a single pass. O(n) time complexity and O(1) space complexity - >>> from collections import Counter - >>> arr1 = [random.choice(COLORS) for _ in range(100)] - >>> arr2 = arr1.copy() - >>> counter = Counter(arr1) - >>> arr1 = [COLORS[0] for _ in range(counter[COLORS[0]])]+[COLORS[1] for _ in range(counter[COLORS[1]])]+\ -[COLORS[2] for _ in range(counter[COLORS[2]])] - >>> dutch_national_flag(arr2) - >>> arr1 == arr2 - True - """ - COLORS = colors - if sequence is None: return - if len(sequence) <= 1: return - l = 0 - mid = 0 - r = len(sequence)-1 - while mid <= r: - if sequence[mid] == COLORS[0]: - sequence[l], sequence[mid] = sequence[mid], sequence[l] - l+=1 - mid+=1 - continue - - if sequence[mid] == COLORS[1]: - mid+=1 - continue - - if sequence[mid] == COLORS[2]: - sequence[r], sequence[mid] = sequence[mid], sequence[r] - r-=1 - continue - - raise ValueError(f"Invalid value {sequence[mid]} inside of sequence. The elements inside the sequence must \ - be in {COLORS} tuple.") - - return - - -def main()->None: - """ - Main method to run doctests - >>> pass - """ - import doctest - doctest.testmod() - - -if __name__ == "__main__": - main() \ No newline at end of file From 34b70daf80f1660c47171de4b1e2de45fd621802 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sat, 23 Oct 2021 17:42:04 +0200 Subject: [PATCH 09/10] Update lru_cache_pythonic.py --- other/lru_cache_pythonic.py | 1 + 1 file changed, 1 insertion(+) diff --git a/other/lru_cache_pythonic.py b/other/lru_cache_pythonic.py index 0b791d394173..b665cc440b20 100644 --- a/other/lru_cache_pythonic.py +++ b/other/lru_cache_pythonic.py @@ -102,6 +102,7 @@ def main()->None: if __name__ == '__main__': import doctest + doctest.testmod() main() From 4f7c0c0bd387cf36751cd65aa8790fe46d538dd1 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Mon, 8 Nov 2021 20:21:08 +0100 Subject: [PATCH 10/10] Remove pontification --- other/lru_cache_pythonic.py | 97 +++++++++++++++++++------------------ 1 file changed, 51 insertions(+), 46 deletions(-) diff --git a/other/lru_cache_pythonic.py b/other/lru_cache_pythonic.py index b665cc440b20..425691ef18cf 100644 --- a/other/lru_cache_pythonic.py +++ b/other/lru_cache_pythonic.py @@ -1,26 +1,27 @@ +""" +This implementation of LRU Cache uses the in-built Python dictionary (dict) which from +Python 3.6 onward maintain the insertion order of keys and ensures O(1) operations on +insert, delete and access. https://docs.python.org/3/library/stdtypes.html#typesmapping +""" 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: - ''' + 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: - ''' - 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. + """ + self.remaining: int = capacity + + def get(self, key: Hashable) -> Any: + """ + This method returns the value associated with the key. + key : A hashable object that is mapped to a value in the LRU cache. + return -> Any object that has been stored as a value in the LRU cache. >>> cache = LRUCache(2) >>> cache.put(1,1) @@ -30,19 +31,18 @@ def get(self, key:Hashable)->Any: 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 + 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: - ''' - 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. + def put(self, key: Hashable, value: Any) -> None: + """ + This method puts the value associated with the key provided in the LRU cache. + key : A hashable object that is mapped to a value in the LRU cache. + value: Any object that is to be associated with the key in the LRU cache. >>> cache = LRUCache(2) >>> cache.put(3,3) >>> cache @@ -50,59 +50,64 @@ def put(self, key:Hashable, value:Any)->None: >>> 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))) + 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: - '''Example test case with LRU_Cache of size 2 + +def main() -> None: + """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} + """ + 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 + 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 + cache.put( + 3, 3 + ) # cache = {1:1, 3:3} key=2 is evicted because it wasn't used recently try: - print(cache.get(2)) + 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 + 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)) + print(cache.get(1)) except KeyError: - print("Key=1 not found in cache") # Prints key not found + print("Key=1 not found in cache") # Prints key not found try: - print(cache.get(3)) # Prints value 3 + print(cache.get(3)) # Prints value 3 except KeyError: print("Key not found in cache") - + try: - print(cache.get(4)) # Prints value 4 + print(cache.get(4)) # Prints value 4 except KeyError: print("Key not found in cache") - -if __name__ == '__main__': +if __name__ == "__main__": import doctest doctest.testmod() main() -