Skip to content

Instantly share code, notes, and snippets.

@AntiKnot
Created July 25, 2021 11:08
Show Gist options
  • Select an option

  • Save AntiKnot/ead544e6299d173947f4e03ef78382bf to your computer and use it in GitHub Desktop.

Select an option

Save AntiKnot/ead544e6299d173947f4e03ef78382bf to your computer and use it in GitHub Desktop.
This piece of LRUCache code is generated by github-copilot.
class LRUCache:
def __init__(self, capacity):
# initialize class variables
self.capacity = capacity
self.cache = {}
self.lru = []
self.lru_count = 0
def get(self, key):
# get value from cache
# if key exists, update LRU
# if key does not exist, return -1
if key in self.cache:
self.lru_count += 1
self.lru.remove(key)
self.lru.append(key)
return self.cache[key]
else:
return -1
def set(self, key, value):
# set key value pair into cache
# if capacity reached, remove LRU value
# if key does not exist, set key value pair
# if key exists, update LRU
if key in self.cache:
self.cache[key] = value
self.lru_count += 1
self.lru.remove(key)
self.lru.append(key)
else:
if self.lru_count < self.capacity:
self.cache[key] = value
self.lru_count += 1
self.lru.append(key)
else:
self.cache.pop(self.lru[0])
self.lru_count -= 1
self.cache[key] = value
self.lru.append(key)
def delete(self, key):
# delete key value pair from cache
# if key exists, update LRU
# if key does not exist, return -1
if key in self.cache:
self.lru_count -= 1
self.lru.remove(key)
self.lru.append(key)
return self.cache.pop(key)
else:
return -1
def clean(self):
# clean cache
# return number of elements removed
count = 0
while self.lru_count > 0:
count += 1
self.cache.pop(self.lru[0])
self.lru_count -= 1
return count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment