-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexcercise3.py
More file actions
63 lines (42 loc) · 1.32 KB
/
excercise3.py
File metadata and controls
63 lines (42 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import collections
import time
class LRUCache:
def __init__(self, capacity,ttl):
self.capacity = capacity
self.cache = collections.OrderedDict()
self.timeToExpiry = ttl
self.expire = time.time() + ttl
self.expires_at = time.time() + ttl
self._expired = False
self.validate()
def lookup(self, key):
try:
value = self.cache.pop(key)
self.cache[key] = value
self.start = 0.0
return value
except KeyError:
raise Exception ("Key not found")
def put(self, key, value):
try:
self.cache.pop(key)
except KeyError:
if len(self.cache) >= self.capacity:
self.cache.popitem(last=False)
self.cache[key] = value
self.start = 0.0
def __iter__(self):
l = list(self.cache.items())
return iter(reversed(l))
def validate(self):
start = time.time()
cache = self.cache
for key,value in cache.items():
if self.expire <= start:
self.cache.pop(key)
cache = LRUCache(2,1)
cache.put("foo",100)
cache.put("bar",200)
time.sleep(2)
for e in cache:
print(e)