繼續學習python中,越來越發現python的方便,也找到了一些python與C/C++的一些相同點與不同點。由於我看的書中缺乏編程練習題,我就在想如何能夠盡快地熟悉python。由於我一直在參加算法競賽,所以就想到了用Python去實現一些數據結構和算法。這類的編程通常不會用到太多的庫,但卻是鍛煉基本功的很好的方法。程序寫好后,可以花幾分鍾時間來總結一下所用到的知識點,這對初學者的效果非常好。下面是書中的一個例子程序,熟悉的八皇后問題,起個拋磚引玉的作用,這段時間我也會用python實現一些更復雜的數據結構。
1 def conflict(state,nextX): 2 nextY=len(state) 3 for i in range(nextY): #注意range是一個半開半閉區間,左閉右開 4 if abs(state[i]-nextX) in (0,nextY-i): #這里是python中我很喜歡的一個特性,比同樣的C語言代碼簡單很多。 5 return True 6 return False 7 8 def queens(num=8,state=()): #默認參數,與C++的規則一樣,從右到左必須都存在默認參數,即如果一個默認參數的右方還存在沒有默認值的參數,會出錯。 9 for pos in range(num): 10 if not conflict(state,pos):# if not語句 11 if len(state)==num-1: 12 yield (pos,) #yield生成器,生成tuple,注意(pos,)這樣的格式 13 else: 14 for result in queens(num,state+(pos,)): #tuple等數據結構的連接也是我很喜歡python的一個原因。 15 yield (pos,)+result 16 def pretty_print(solution): 17 def line(pos,length=len(solution)):#函數定義中定義函數,這一點與C/C++都不同,需要額外注意。 18 return '.'*pos+'X'+'.'*(length-pos-1) 19 for pos in solution: 20 print line(pos) 21 #print list(queens(4)) 22 #print len(list(queens(8))) 23 import random 24 pretty_print(random.choice(list(queens(8))))
"學而不思則惘"。總結十分重要!
參考資料:《Beginning Python From Novice to Professional 2nd Edition》
如果我的文章對您有用,請推薦一下,非常感謝!