最常用的排序 -- 快速排序
def quickSort(array):
smaller = []
greater = []
if len(array) <= 1:
return array
base = array.pop()
for x in array:
if x < base:
smaller.append(x)
else:
greater.append(x)
return quickSort(smaller) + [base] + quickSort(greater)
arrayList = [9, 12, 25, 5, 21, 3, 7, 11, 85]
quickSort(arrayList)
[3, 5, 7, 9, 11, 12, 21, 25, 85]
解密QQ號 -- 隊列
def extractQQNumber(qq, result=[]):
"""
Python技巧:利用Python默認參數(shù)再次調(diào)用不重新計算的特性獲得返回值
(參考《編寫高質(zhì)量代碼 改善Python程序的91個建議》建議32:警惕默認參數(shù)潛在的問題)
"""
num = qq.pop(0)
result.append(num)
if len(qq) > 0:
num = qq.pop(0)
qq.append(num)
extractQQNumber(qq)
return result
qq = '631758924'
extractQQNumber([i for i in qq])
['6', '1', '5', '9', '4', '7', '2', '8', '3']
坑爹的奧數(shù):口口口+口口口=口口口
代碼參考網(wǎng)上的,原諒我自己不太理解蹋绽“疟校《啊哈!算法》中深度優(yōu)先搜索基本模型已經(jīng)體現(xiàn)了卸耘。
perm_lst = []
def permutation(lst):
if lst == []: # 判斷邊界
if perm_lst[0]*100 + perm_lst[1]*10 + perm_lst[2] + perm_lst[3]*100 + perm_lst[4]*10 + perm_lst[5] == perm_lst[6]*100 + perm_lst[7]*10 + perm_lst[8]:
print(perm_lst)
else:
for elem in lst: # 嘗試每一種可能
perm_lst.append(elem)
rest_lst = lst[:]
rest_lst.remove(elem)
permutation(rest_lst) # 繼續(xù)下一步
perm_lst.pop() # 回收
## 測試
permutation([i for i in range(1, 10)])
## 輸出結(jié)果:
[1, 2, 4, 6, 5, 9, 7, 8, 3]
[1, 2, 5, 7, 3, 9, 8, 6, 4]
[1, 2, 7, 3, 5, 9, 4, 8, 6]
···
[7, 8, 3, 1, 6, 2, 9, 4, 5]
[7, 8, 4, 1, 5, 2, 9, 3, 6]