前段时间心血来潮，看了点Python的东西，推荐两个比较好的学习Python的网站：Python简明教程以及byr论坛十大的帖子里推荐的一个网站：LcodeTHW

现在准备把这些天看得东西码上来，总结一下，包括了二分查找，选择排序，冒泡排序，归并排序以及简单的0-1背包问题等。

二分查找：（其中calls 是总共执行次数）

def bsearch(s,e,first,last,calls):
print first,last,calls
if(last-first)<2:
return s[last]==e or s[first]==e
mid = (first + last)/2
if e== s[mid]:
return True
if e>s[mid]:
return bsearch(s,e,mid+1,last,calls+1)
return bsearch(s,e,first,mid-1,calls+1)

选择排序O(n^2)：

def selSort(s):
for i in range(len(s)):
print s
index = i
minvalue = s[i]
for j in range(i+1,len(s)):
if s[j]<minvalue:
index = j
minvalue = s[j]
temp = s[i]
s[i] = s[index]
s[index] = temp

return s

冒泡排序O(n^2)

def bubbleSort(s):
flag = 1
for i in range(len(s)):
if flag==0:
break
print s
for j in range(len(s)-1):
if s[j]>s[j+1]:
temp = s[j]
s[j] = s[j+1]
s[j+1] = temp
flag = 1
else:
flag = 0

归并排序O(nlogn)：典型的divide and conquer两个步骤

def merge(left,right):
result = []
i = 0
j = 0
while i<len(left) and j<len(right):
if left[i] <= right[j]:
result.append(left[i])
i+=1
else :

result.append(right[j])
j+=1
while i < len(left):
result.append(left[i])
i+=1
while j < len(right):
result.append(right[j])
j+=1
return result

def mergeSort(s):
print s
if len(s)<2:
return s
mid = len(s)/2
left = mergeSort(s[:mid])
right = mergeSort(s[mid:])
together = merge(left,right)
print 'merged',together
return together

背包问题：简单的DP,空间换时间。

def fastMaxVal(w, v, i, aW, m):

global numCalls
numCalls += 1
try: return m[(i, aW)]
except KeyError:
if i == 0:
if w[i] <= aW:
m[(i, aW)] = v[i]
return v[i]
else:
m[(i, aW)] = 0
return 0
without_i = fastMaxVal(w, v, i-1, aW, m)
if w[i] > aW:
m[(i, aW)] = without_i
return without_i
else: with_i = v[i] + fastMaxVal(w, v, i-1, aW - w[i], m)
res = max(with_i, without_i)
m[(i, aW)] = res
return res

• 本文已收录于以下专栏：

举报原因： 您举报文章：Something About Python 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)