1. pre-fork的多进程模型
在web server中广泛使用,即父进程先创建listen socket,然后fork子进程,所有子进程都在accpet同一个socket,这种方法去掉了fork的开销,在早期的linux版本中会存在惊群现象,意思是当有一个连接到来时,所有的进程都会被唤醒,但现在不会
2. 如何求一个数是不是平方数:最简单的方法,对1...n 进行binary search
3. 求二叉树里两个节点的最低公共祖先: 用一个stack,先根遍历这棵树,当两个节点都已访问后,堆栈里的节点即是
4.spell checker:首先对字典里的每一个词进行加工:
def edits1(word):
s = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in s if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in s if len(b)>1]
replaces = [a + c + b[1:] for a, b in s for c in alphabet if b]
inserts = [a + c + b for a, b in s for c in alphabet]
return set(deletes + transposes + replaces + inserts)
这样是计算出这个词的edit1 的距离,然后对输入词查找是否在这个set中,可以继续这样操作得到编辑距离为2的集合
完成的代码如下,参考(http://www.norvig.com/spell-correct.html)
import re, collections
def words(text): return re.findall('[a-z]+', text.lower())
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
NWORDS = train(words(file('big.txt').read()))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits1(word):
s = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in s if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in s if len(b)>1]
replaces = [a + c + b[1:] for a, b in s for c in alphabet if b]
inserts = [a + c + b for a, b in s for c in alphabet]
return set(deletes + transposes + replaces + inserts)
def known_edits2(word):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
def known(words): return set(w for w in words if w in NWORDS)
def correct(word):
candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
return max(candidates, key=NWORDS.get)