function 參數先排位置再對參數名稱

如果沒有指定要丟的參數名稱, python 就會照順序排. 如果順序對不起來就會 error.
>>> def f(a,b,c):
 print 'a:', a, 'b:', b, 'c:', c

 
>>> f(1,2,3)
a: 1 b: 2 c: 3
>>> f(1,c=3,b=2)
a: 1 b: 2 c: 3
>>> f(1,2,c=3)
a: 1 b: 2 c: 3
>>> f(1,2,b=2) # 第二個參數已經指定了, 所以就不能再指定 b

Traceback (most recent call last):
  File "", line 1, in 
    f(1,2,b=2)
TypeError: f() got multiple values for keyword argument 'b'

>>> f(c=3,2,a=1)
SyntaxError: non-keyword arg after keyword arg

>>> f(a=1,2,3)
SyntaxError: non-keyword arg after keyword arg

字串 format

帶入 dict 的值, 如果用 format api, dictionary 要帶 ** 去展開 key-value
>>> m = {'a':1.1234, "b":"qq"}
>>> '%(a)1.1f %(a)s %(b)s' %m
'1.1 1.1234 qq'


>>> '{a:1.1f} {a:s} {b:s}'.format(m) # illegal, must use **m

Traceback (most recent call last):
  File "", line 1, in 
    '{a:1.1f} {a:s} {b:s}'.format(m)
KeyError: 'a'

>>> '{a:1.1f} {a:s} {b:s}'.format(**m) # illegal, a is float type

Traceback (most recent call last):
  File "", line 1, in 
    '{a:1.1f} {a:s} {b:s}'.format(**m)
ValueError: Unknown format code 's' for object of type 'float'

>>> '{a:1.1f} {b:s}'.format(**m)
'1.1 qq'

tuple 就是不可變的 list

tuple 就是不可變的 list.
>>> list = ['c',[1,2,3]]
>>> tuple = ('c',(1,2,3))
>>> list[0]
'c'
>>> list[1]
[1, 2, 3]
>>> tuple[0]
'c'
>>> tuple[1]
(1, 2, 3)
>>> list[0] = 'q'
>>> list[0]
'q'
>>> list[1]
[1, 2, 3]
>>> tuple[0] = 'q'

Traceback (most recent call last):
  File "", line 1, in 
    tuple[0] = 'q'
TypeError: 'tuple' object does not support item assignment

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...