2012年4月2日 星期一

[Python Std Library] Data Types : bisect — Array bisection algorithm


翻譯自 這裡
Preface :
這個模組提供 basic bisection algorithm 來維護一個 Ordered list, 每次插入 element 後都不必重新 sorting 以減少 comparison 的 effort. 先來看看這個模組上提供的方法 :
- bisect.bisect_left(a, x, lo=0, hi=len(a))
Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted.

The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i]) for the left side and all(val >= x for val in a[i:hi]) for the right side. Check example :
>>> h = [1, 2, 4, 6, 7, 7, 8, 9]
>>> bisect_left(h, 7)
4
>>> h[0:4]
[1, 2, 4, 6]
>>> h[4:]
[7, 7, 8, 9]

- bisect.bisect_right(a, x, lo=0, hi=len(a))
- bisect.bisect(a, x, lo=0, hi=len(a))
Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a.
>>> h = [1, 2, 4, 6, 7, 7, 8, 9]
>>> bisect(h, 7)
6
>>> h[0:6] # 在位置 6 以前的值會小於等於 7
[1, 2, 4, 6, 7, 7]
>>> h[6:] # 在位置 6 (含) 以後的位置大於 7
[8, 9]

- bisect.insort_left(a, x, lo=0, hi=len(a))
Insert x in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x) assuming that a is already sorted. Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.
>>> h = [1, 2, 4, 6, 7, 7, 8, 9]
>>> insort_left(h, 6)
>>> h
[1, 2, 4, 6, 6, 7, 7, 8, 9]
>>> insort_left(h, 6, lo=6) # 從位置 6 到 len(h) 中進行插入.
>>> h
[1, 2, 4, 6, 6, 7, 6, 7, 8, 9]

- bisect.insort_right(a, x, lo=0, hi=len(a))
- bisect.insort(a, x, lo=0, hi=len(a))
Similar to insort_left(), but inserting x in a after any existing entries of x.

Searching Sorted Lists :
透過下面的函數包裝, 讓你輕鬆從 sorted list 進行搜尋 :
  1. def index(a, x):  
  2.     'Locate the leftmost value exactly equal to x'  
  3.     i = bisect_left(a, x)  
  4.     if i != len(a) and a[i] == x:  
  5.         return i  
  6.     raise ValueError  
  7.   
  8. def find_lt(a, x):  
  9.     'Find rightmost value less than x'  
  10.     i = bisect_left(a, x)  
  11.     if i:  
  12.         return a[i-1]  
  13.     raise ValueError  
  14.   
  15. def find_le(a, x):  
  16.     'Find rightmost value less than or equal to x'  
  17.     i = bisect_right(a, x)  
  18.     if i:  
  19.         return a[i-1]  
  20.     raise ValueError  
  21.   
  22. def find_gt(a, x):  
  23.     'Find leftmost value greater than x'  
  24.     i = bisect_right(a, x)  
  25.     if i != len(a):  
  26.         return a[i]  
  27.     raise ValueError  
  28.   
  29. def find_ge(a, x):  
  30.     'Find leftmost item greater than or equal to x'  
  31.     i = bisect_left(a, x)  
  32.     if i != len(a):  
  33.         return a[i]  
  34.     raise ValueError  
使用範例如下 :
>>> d = [1, 2, 3, 4, 4, 6, 7, 9]
>>> index(d, 5)
Traceback (most recent call last):
File "", line 1, in
File "bisect_ser.py", line 8, in index
raise ValueError
ValueError
>>> index(d, 4) # 如果有數字4, 傳回最左邊位置 
3
>>> find_le(d, 6) # 小於等於 6
6
>>> find_lt(d, 6) # 小於 6
4
>>> find_gt(d, 6) # 大於 6
7
>>> find_ge(d, 6) # 大於等於 6
6

Other Examples :
考慮我們要為成績分等 : 60 以下為 F ; 60~69為D ; 70~79為C ; 80~89為B ; 90~100為A. 透過模組 bisect 便可以很輕鬆辦到. 透過函數 bisect() 來對 [60, 70, 80, 90] 進行 indexing ; 可以知道小於 60 會得到 0 ; 60~69會得到1 ; 70~79會得到2 以此類推. 因此我們可以透過返回的 index 取出 'FDCBA' 對應位置的字元便可以達成 :


另外再使用函數 sorted() 與 bisect() 上的差別是 bisect() 並沒有所謂的 reverse 的功能且使用上是在參數已經是 ordered 條件下才有意義. 因此在使用上彼此是相輔相成, 來看看下面的範例 :
>>> from bisect import *
>>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
>>> data.sort(key=lambda r: r[1]) # 使用 tuple 的數字對 data 進行 sorting
>>> data
[('black', 0), ('blue', 1), ('red', 5), ('yellow', 8)]
>>> keys = [r[1] for r in data] # 取出 data 中的 sorted 數字
>>> keys
[0, 1, 5, 8]
>>> data[bisect_left(keys, 0)] # 取出數字 0 的位置, 並利用該位置取出 data 數字是 0 的 tuple
('black', 0)
>>> data[bisect_left(keys, 2)] # 取出大於等於 2 的位置, 再以該位置取出 data 中的 tuple
('red', 5)
This message was edited 14 times. Last update was at 03/04/2012 09:24:08

[Python Std Library] Data Types : collections — High-performance container datatypes

翻譯自 這裡 
Preface : 
在這個模組支援了 container 需求並提供不同的實作, 讓你在已經支援的 dict, list, set 與 tuple 外有其他選擇. 底下此模組提供的 container 種類 : 
 

Counter objects : 
此類別提供快速統計資料的處理, 先看範例如下 : 
>>> import re
>>> words = re.findall('\w+', open('doc.txt').read().lower())
>>> from collections import Counter
>>> Counter(words).most_common(10) # Find the ten most common words in doc.txt
[('the', 18), ('is', 9), ('to', 6), ('list', 6), ('of', 6), ('and', 6), ('are', 5), ('counts', 5), ('for', 4), ('length', 4)]

可以透過下面建構子建立物件 : 
- class collections.Counter([iterable-or-mapping]) 
A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

Count 提供 dict 的介面, 比較要注意的是如果你嘗試 access 一個不存在的鍵值, 0 會被返回而不是丟出 KeyError : 
>>> from collections import Counter
>>> c = Counter(['eggs', 'ham'])
>>> c['eggs']
1
>>> c['bacon']
0

接著我們來看看物件上有什麼函數可以用 : 
- elements() 
Return an iterator over elements repeating each as many times as its count. Elements are returned in arbitrary order. If an element’s count is less than one, it will be ignored.
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

- most_common([n]) 
Return a list of the n most common elements and their counts from the most common to the least. If n is not specified, this method returns all elements in the counter. Elements with equal counts are ordered arbitrarily :
>>> Counter('abracadabrafg').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]

- subtract([iterable-or-mapping]) 
Elements are subtracted from an iterable or from another mapping (or counter). Like dict.update() but subtracts counts instead of replacing them. Both inputs and outputs may be zero or negative.
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

- update([iterable-or-mapping]) 
Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them. Also, the iterableis expected to be a sequence of elements, not a sequence of (key, value) pairs.

底下是常見操作整理 : 
sum(c.values()) # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
c.most_common()[:-n:-1] # n least common elements
c += Counter() # remove zero and negative counts

更方便與直覺的, 某些數學運算子支援如下 : 
>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d # add two counters together: c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d # intersection: min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d # union: max(c[x], d[x])
Counter({'a': 3, 'b': 2})

deque objects : 
首先來看它的建構子 : 
- class collections.deque([iterable[, maxlen]]) 
Returns a new deque object initialized left-to-right (using append()) with data from iterable. If iterable is not specified, the new deque is empty.

Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.

Deque 物件支援下面方法 : 
- append(x) 
Add x to the right side of the deque.

- appendleft(x) 
Add x to the left side of the deque.

- clear() 
Remove all elements from the deque leaving it with length 0.

- count(x) 
New in version 2.7.
Count the number of deque elements equal to x.

- extend(iterable) 
Extend the right side of the deque by appending elements from the iterable argument.

- extendleft(iterable) 
Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument.

- pop() 
Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError.

- popleft() 
Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.

- remove(value) 
New in version 2.5.
Removed the first occurrence of value. If not found, raises a ValueError.

- reverse() 
New in version 2.7.
Reverse the elements of the deque in-place and then return None.

- rotate(n) 
Rotate the deque n steps to the right. If n is negative, rotate to the left. Rotating one step to the right is equivalent to: d.appendleft(d.pop()).

在使用 deque 必須知道在 access 兩端的 element 所需的時間為 O(1) ; 但是在 random access 中間的 element 所需時間為 O(n). 因此如果你需要常常 random 存取中間的元素建議使用 list來實作. 底下為其使用範例 : 
>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
... print elem.upper()
G
H
I

>>> d.append('j') # add a new entry to the right side
>>> d.appendleft('f') # add a new entry to the left side
>>> d # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
>>> list(d) # list the contents of the deque
['g', 'h', 'i']
>>> d[0] # peek at leftmost item
'g'
>>> d[-1] # peek at rightmost item
'i'

>>> list(reversed(d)) # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d # search the deque
True
>>> d.extend('jkl') # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1) # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1) # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

>>> deque(reversed(d)) # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear() # empty the deque
>>> d.pop() # cannot pop from an empty deque
Traceback (most recent call last):
File "", line 1, in -toplevel-
d.pop()
IndexError: pop from an empty deque

>>> d.extendleft('abc') # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])

更多的 deque 應用可以參考 deque Recipes 

defaultdict objects : 
此類別的建構子如下 : 
- class collections.defaultdict([default_factory[, ...]]) 
Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

因為此類別提供與 dict 相同的運算與函式, 接著我們直接來看範例 : 
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

如果你將 default_factory 設為 int 方便進行 counting 的計算 : 
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1 # 當鍵值第一次出現時, 初始值為 int() = 0
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

如果將 default_factory 設為 set : 
>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
... d[k].add(v)
...
>>> d.items()
[('blue', set([2, 4])), ('red', set([1, 3]))] # duplicate ('red', 1) will be drop

namedtuple() Factory Function for Tuples with Named Fields : 
此類別提供比 tuple 更強的功能與方便的操作, 建構子如下 : 
- collections.namedtuple(typename, field_names[, verbose=False][, rename=False]) 
Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful __repr__() method which lists the tuple contents in a name=value format.

The field_names are a sequence of strings such as ['x', 'y']. Alternatively, field_names can be a single string with each fieldname separated by whitespace and/or commas, for example 'x y' or 'x, y'.

Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, print, or raise.

If rename is true, invalid fieldnames are automatically replaced with positional names. For example, ['abc', 'def', 'ghi', 'abc'] is converted to ['abc', '_1', 'ghi', '_3'], eliminating the keyword def and the duplicate fieldname abc.

If verbose is true, the class definition is printed just before being built.

Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.

接著來看範例如何使用 : 
>>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
...(略)...
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> p # readable __repr__ with a name=value style
Point(x=11, y=22)

除了原本 tuple 舊有的函數與屬性, named tuple 支援以下新增的函數與屬性, 為了避免名稱上的 conflict, 名稱前會加上 underscore : 
- classmethod somenamedtuple._make(iterable) 
Class method that makes a new instance from an existing sequence or iterable.
>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)

- somenamedtuple._asdict() 
Return a new OrderedDict which maps field names to their corresponding values :
>>> p._asdict()
OrderedDict([('x', 11), ('y', 22)])

- somenamedtuple._replace(kwargs) 
Return a new instance of the named tuple replacing specified fields with new values :
>>> p = Point(x=11, y=22)
>>> p._replace(x=33) # 返回新物件
Point(x=33, y=22)
>>> p
Point(x=11, y=22)

- somenamedtuple._fields 
Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples :
>>> p._fields
('x', 'y')
>>> Color = namedtuple('Color', 'red green blue')
>>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)

如果你要從 named tuple 的某個 field 取出值的話, 可以使用 Built-in 函數 getattr() : 
>>> getattr(p, 'x') # p 為 named tuple ; 'x' 為 field 的名稱.
11

如果你要從 dictionray 轉成 named tuple, 可以使用 double-star-operator : 
>>> d = {'x': 11, 'y': 22}
>>> Point(**d)
Point(x=11, y=22)

既然 named tuple 也是類別, 所以你也可以繼承並新增客製函數 : 
 

OrderedDict objects : 
OrderedDict 類別與一般你使用到的 dict 內建類別沒有多大差異, 唯一不同是此類別會記住你 inserted key 的順序, 所以之後你取出時便可以按照插入的順序取出. 首先來看看建構子 : 
- class collections.OrderedDict([items]) 
New in version 2.7.
Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

接著來看物件上的方法 : 
- OrderedDict.popitem(last=True) 
This method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false.

接著來看使用上的範例, 首先是透過 sorted() 與指定 key 的方式讓你決定 ordered dictionary 的順序 : 
 

Supplement : 
* Collections Abstract Base Classes

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...