#!/usr/bin/env python3
# -*- coding:UTF-8 -*-

#Copyright (c) 1986 Nick Wong.
#Copyright (c) 2016-2026 TP-NEW Corp.
# License: TP-NEW (www.tp-new.com)

__author__ = "Nick Wong"

'''
常用内建模块      collections(集合模块)
'''

## namedtuple
p = (1,3)
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1,2)
print(p.x ,'   ',p.y)
print('isinstance(p,Point)   ',isinstance(p,Point))
print('isinstance(p,tuple)  ', isinstance(p,tuple))


## deque
# deque除了实现list的append()和pop()外，还支持appendleft()和popleft()，这样就可以非常高效地往头部添加或删除元素。
from collections import deque
q = deque(['a', 'b', 'c'])
q.append('x')
q.appendleft('y')
print('q :',q)

## defaultdict
# 使用dict集合时，如果引用的Key不存在，就会抛出KeyError。如果希望key不存在时，返回一个默认值，就可以用defaultdict
from collections import defaultdict
dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
print('dd[\'key1\'] 值存在:',dd['key1'])
print('dd[\'key2\'] 值不存在:',dd['key2'])

## OrderedDict
#使用dict时，Key是无序的。在对dict做迭代时，我们无法确定Key的顺序,可以用OrderedDict保持Key的顺序
#OrderedDict的Key会按照插入的顺序排列，不是Key本身排序
from collections import OrderedDict
d = dict([('a',1),('b',2),('c',3),('d',4),('e',5),('f',6),('g',7),('h',8),('i',9)])
print('打印原始无序的集合d :',d)
od = OrderedDict([('a',1),('b',2),('c',3),('d',4),('e',5),('f',6),('g',7),('h',8),('i',9)])
print('打印有序的集合od :',od)

#OrderedDict可以实现一个FIFO(先进先出)的dict(集合),当容量超出限制时，先删除最早添加的Key
class LastUpdatedOrderedDict(OrderedDict):
    def __init__(self, capacity):
        super(LastUpdatedOrderedDict, self).__init__()
        self._capacity = capacity

    def __setitem__(self, key, value):
        containsKey = 1 if key in self else 0
        if len(self) - containsKey >= self.__capacity:
            last = self.popitem(last=False)
            print('remove:', last)
        if containsKey:
            del self[key]
            print('set:', (key, value))
        else:
            print('add:', (key,value))
        OrderedDict.__setitem__(self, key, value)

if __name__ == '__main__':
    LastUpdatedOrderedDict(od)

## Counter 一个简单的计数器 如:统计字符出现个数
from collections import Counter
c = Counter()
for ch in 'nick-huang-cc':
    c[ch] = c[ch] + 1
print('c ; ',c)