from collections import namedtuple
from collections import deque
from collections import OrderedDict
def nametuple_example():
Person = namedtuple("hahaha", "name, age, gender")
alice = Person(name="alice", age=30, gender="female")
print(alice.name, alice.age, alice.gender)
print(type(alice))
def deque_example():
q = deque("abc")
print(q)
q.appendleft("123")
print(q)
q.append("e")
print(q)
q.pop()
print(q)
def orderdict_example():
ord = OrderedDict()
ord['a'] = 'a'
ord['b'] = 'b'
ord['c'] = 'c'
print(ord)
ord.popitem(last=False)
print(ord)
ord['d'] = 'd'
print(ord)
ord.popitem(last=True)
print(ord)
class LRUCache:
def __init__(self, capacity=10):
self.ord = OrderedDict()
self.capacity = capacity
def get(self, key):
if key in self.ord:
value = self.ord[key]
self.ord.move_to_end(key)
return value
else:
return -1
def put(self, key, value):
if key in self.ord:
del self.ord[key]
self.ord[key] = value
else:
self.ord[key] = value
if len(self.ord) > self.capacity:
self.ord.popitem(last=False)
def show(self):
print(self.ord)
def LRUCache_example():
lrucache = LRUCache(capacity=3)
lrucache.put(key='a', value='a')
lrucache.put(key='b', value='b')
lrucache.put(key='c', value='c')
lrucache.put(key='a', value='a')
lrucache.put(key='d', value='d')
lrucache.put(key='e', value='e')
lrucache.show()
if __name__ == "__main__":
nametuple_example()
deque_example()
orderdict_example()
LRUCache_example()
console output
alice 30 female
<class '__main__.hahaha'>
deque(['a', 'b', 'c'])
deque(['123', 'a', 'b', 'c'])
deque(['123', 'a', 'b', 'c', 'e'])
deque(['123', 'a', 'b', 'c'])
OrderedDict([('a', 'a'), ('b', 'b'), ('c', 'c')])
OrderedDict([('b', 'b'), ('c', 'c')])
OrderedDict([('b', 'b'), ('c', 'c'), ('d', 'd')])
OrderedDict([('b', 'b'), ('c', 'c')])
OrderedDict([('a', 'a'), ('d', 'd'), ('e', 'e')])