可愛的python習題答案_第1頁
可愛的python習題答案_第2頁
可愛的python習題答案_第3頁
可愛的python習題答案_第4頁
可愛的python習題答案_第5頁
已閱讀5頁,還剩37頁未讀 繼續免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、可愛的python習題答案 status 校對 lizzie 完成度100% CDays-51. 計算今年是閏年嘛?判斷閏年條件, 滿足年份模400為0, 或者模4為0但模100不為0. o 源代碼 Toggle line numbers 1 #coding:utf-8 2 '''cdays-5-exercise-1.py 判斷今年是否是閏年 3 note: 使用了import, time模塊, 邏輯分支, 字串格式化等 4 ''' 5 6 import time #導入time模塊 7 thisyear = time.localtim

2、e()0 #獲取當前年份 8 if thisyear % 400 = 0 or thisyear % 4 =0 and thisyear % 100 <> 0: #判斷閏年條件, 滿足模400為0, 或者模4為0但模100不為0 9 print 'this year %s is a leap year' % thisyear 10 else: 11 print 'this year %s is not a leap year' % thisyear 12 o 運行截屏 2. 利用python作為科學計算器。熟悉Python中的常用運算符,并分別求出表

3、達式12*34+78-132/6、(12*(34+78)-132)/6、(86/40)*5的值。并利用math模塊進行數學計算,分別求出145/23的余數,0.5的sin和cos值注意sin和cos中參數是弧度制表示提醒:可通過import math; help("math")查看math幫助. o 源代碼 Toggle line numbers 1 #coding:utf-8 2 '''cdays-5-exercise-2.py 求表達式的值 3 note: 根本表達式運算, 格式化輸出, math模塊 4 see: math模塊使用可參考 :/d

4、/lib/module-math.html 5 ''' 6 7 x = 12*34+78-132/6 #表達式計算 8 y = (12*(34+78)-132)/6 9 z = (86/40)*5 10 11 print '12*34+78-132/6 = %d' % x 12 print '(12*(34+78)-132)/6 = %d' % y 13 print '(86/40)*5 = %f' % z 14 15 import math #導入數學計算模塊 16 17 a = math.f

5、mod(145, 23) #求余函式 18 b = math.sin(0.5) #正弦函式 19 c = math.cos(0.5) #余弦函式 20 21 print '145/23的余數 = %d' % a 22 print 'sin(0.5) = %f' %b 23 print 'cos(0.5) = %f' %c 24 o 運行截屏 3. 找出0100之間的所有素數。 o 源代碼 Toggle line numbers 1 #coding:utf-8 2 '''cdays-5-exercise-3.py 求0100

6、之間的所有素數 3 note: for循環, 列表類型 4 see: math模塊使用可參考 ://lib/module-math.html 5 ''' 6 7 from math import sqrt 8 9 N = 100 10 #根本的方法 11 result1 = 12 for num in range(2, N): 13 f = True 14 for snu in range(2, int(sqrt(num)+1): 15 if num % snu = 0: 16 f = False 17 break 18 if f: 19

7、result1.append(num) 20 print result1 21 22 #更好的方法 23 result2 = p for p in range(2, N) if 0 not in p% d for d in range(2, int(sqrt(p)+1) 24 print result2 25 o 運行截屏 CDays-41. os 模塊中還有哪些功能可以使用? - 提示使用 dir()和help() o os模塊中還有很多功能,主要的有以下些: § os.error, os.path, os.popen, os.stat_result, os.sys, os.sys

8、tem等等等,詳細可參見dir("os")和Python幫助文檔help("os") 2. open() 還有哪些模式可以使用? o open()有以下幾種模式: § 'r': 以只讀方式翻開已存在文件,假設文件不存在那么拋出異常。此方式是默認方式 § 'U'或者'rU': Python慣例構造了通用換行支持;提供'U'模式以文本方式翻開一個文件,但是行可能隨時結束:Unix的結束符規定為'n',蘋果系統那么為'r',還有Windows規定

9、為'rn',所有這些規定在Python程序中統一為'n'. § 'w': 以可寫方式翻開存在或者不存在的文件,假設文件不存在那么先新建該文件,假設文件存在那么覆蓋該文件 § 'a': 用于追加,對unix系統而言,所有的內容都將追加到文件末尾而不管指針的當前位置如何 § 'b': 以二進制方式翻開。翻開一個二進制文件必須用該模式。增加'b'模式是用來兼容系統對當二進制和文本文件的處理不同 § 'r+','w+'和'a+&

10、#39;以更新方式翻開文件(注意'w+'覆蓋文件) 3. 嘗試for . in .循環可以對哪些數據類型進行操作? o for.in循環對于任何序列列表,元組,字符串都適用。但從廣義說來可以使用任何種類的由任何對象組成的序列 4. 格式化聲明,還有哪些格式可以進行約定? o 格式化申明 o 詳細: ://lib/typesseq-strings.html (精巧地址: :/bit.ly/2TH7cF) § d Signed integer decimal. § i Signed integer decimal. § o

11、 Unsigned octal. § u Unsigned decimal. § x Unsigned hexadecimal (lowercase). § X Unsigned hexadecimal (uppercase). § e Floating point exponential format (lowercase). § E Floating point exponential format (uppercase). § f Floating point decimal format. § F Floating

12、point decimal format. § g Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise. § G Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise. 

13、7; c Single character (accepts integer or single character string). § r String (converts any python object using repr(). § s String (converts any python object using str(). § % No argument is converted, results in a "%" character in the result. 5. 現在的寫入文件模式好嘛? 有改良的余地? o CDay

14、-4-5.py 好在哪里? Toggle line numbers 1 # coding : utf-8 2 3 import os 4 5 export = "" 6 for root, dirs, files in os.walk('/media/cdrom0'): 7 export+="n %s;%s;%s" % (root,dirs,files) 8 open('mycd2.cdc', 'w').write(export) 9 o CDay-4-6.py又更加好在哪里? Toggle line nu

15、mbers 1 # coding : utf-8 2 3 import os 4 5 export = 6 for root, dirs, files in os.walk('/media/cdrom0'): 7 export.append("n %s;%s;%s" % (root,dirs,files) 8 open('mycd2.cdc', 'w').write(''.join(export) 9 o CDay-4-5.py中使用了字符串的+連接,而CDay-4-6.py中是利用join。字符串的join要

16、比+操作效率高。因為對象的反復+,比一次性內建處理,要浪費更多的資源。 6. 讀取文件cdays-4-test.txt內容,去除空行和注釋行后,以行為單位進行排序,并將結果輸出為cdays-4-result.txt。 o cdays-4-test.txto #some wordsoo Sometimes in life,o You find a special friend;o Someone who changes your life just by being part of it.o Someone who makes you laugh until you can't stop

17、;o Someone who makes you believe that there really is good in the world.o Someone who convinces you that there really is an unlocked door just waiting for you to open it.o This is Forever Friendship.o when you're down,o and the world seems dark and empty,o Your forever friend lifts you up in spi

18、rits and makes that dark and empty worldo suddenly seem bright and full.o Your forever friend gets you through the hard times,the sad times,and the confused times.o If you turn and walk away,o Your forever friend follows,o If you lose you way,o Your forever friend guides you and cheers you on.Your f

19、orever friend holds your hand and tells you that everything is going to be okay. o 源代碼 Toggle line numbers 1 #coding:utf-8 2 '''cdays-4-exercise-6.py 文件根本操作 3 note: 文件讀取寫入, 列表排序, 字符串操作 4 see: 字符串各方法可參考hekp(str)或Python在線文檔 ://lib/string-methods.html 5 ''' 6 7 f

20、= open('cdays-4-test.txt', 'r') #以讀方式翻開文件 8 result = list() 9 for line in f.readlines(): #依次讀取每行 10 line = line.strip() #去掉每行頭尾空白 11 if not len(line) or line.startswith('#'): #判斷是否是空行或注釋行 12 continue #是的話,跳過不處理 13 result.append(line) #保存 14 result.sort() #排序結果 15 print result

21、 16 open('cdays-4-result.txt', 'w').write('%s' % 'n'.join(result) #保存入結果文件 17 o 運行截屏 CDays-31. 根據DiPy 10.6. 處理命令行參數( :/ /diveintopython/scripts_and_streams/command_line_arguments.html 精巧地址: :/bit.ly/1x5gMw)使用getopt.getopt()優化當前功能函式。 o 源代碼 Toggle line nu

22、mbers 1 # coding=utf-8 2 '''Lovely Python -3 PyDay 3 PyCDC v0.3 4 see: :/ /diveintopython/scripts_and_streams/command_line_arguments.html 5 ''' 6 import os,sys 7 import getopt #導入getopt模塊 8 9 CDROM = '/media/cdrom0' 10 def cdWalker(cdrom,cdcfile): 11 ex

23、port = "" 12 for root, dirs, files in os.walk(cdrom): 13 export+="n %s;%s;%s" % (root,dirs,files) 14 open(cdcfile, 'w').write(export) 15 16 def usage(): 17 print '''PyCDC 使用方式: 18 python cdays-3-exercise-1.py -d cdc -k 中國火 19 #搜索 cdc 目錄中的光盤信息,尋找有“中國火字樣的文件或是目錄,

24、在哪張光盤中 20 ''' 21 try: 22 opts, args = getopt.getopt(sys.argv1:, 'hd:e:k:') 23 except getopt.GetoptError: 24 usage() 25 sys.exit() 26 27 if len(opts) = 0: 28 usage() 29 sys.exit() 30 31 c_path = '' 32 for opt, arg in opts: 33 if opt in ('-h', '-help'): 34 u

25、sage() 35 sys.exit() 36 elif opt = '-e': 37 #判別sys.argv2中是否有目錄,以便進行自動創立 38 #cdWalker(CDROM, arg) 39 print "記錄光盤信息到 %s" % arg 40 elif opt = '-d': 41 c_path = arg 42 elif opt = '-k': 43 if not c_path: 44 usage() 45 sys.exit() 46 #進行文件搜索 47 2. 讀取某一簡單索引文件cdays-3-test.tx

26、t,其每行格式為文檔序號 關鍵詞,現需根據這些信息轉化為倒排索引,即統計關鍵詞在哪些文檔中,格式如下:包含該關鍵詞的文檔數 關鍵詞 => 文檔序號。其中,原索引文件作為命令行參數傳入主程序,并設計一個collect函式統計 "關鍵字<>序號" 結果對,最后在主程序中輸出結果至屏幕。 o cdays-3-test.txt 內容:o 1 key1o 2 key2o 3 key1o 7 key3o 8 key2o 10 key1o 14 key2o 19 key4o 20 key130 key3o 源代碼 Toggle line numbers 1 #codin

27、g:utf-8 2 '''cdays-3-exercise-2.py 字典的使用 3 not: 使用sys.args, 字典操作, 函式調用 4 see: sys模塊參見help(sys) 5 ''' 6 7 import sys #導入sys模塊 8 9 def collect(file): 10 ''' 改變 key-value對為value-key對 11 param file: 文件對象 12 return: 一個dict包含value-key對 13 ''' 14 result = 15

28、for line in file.readlines(): #依次讀取每行 16 left, right = line.split() #將一行以空格分割為左右兩局部 17 if result.has_key(right): #判斷是否已經含有right值對應的key 18 resultright.append(left) #假設有,直接添加到resultright的值列表 19 else: 20 resultright = left #沒有,那么新建resultright的值列表 21 return result 22 23 if _name_ = "_main_": 2

29、4 if len(sys.argv) = 1: #判斷參數個數 25 print 'usage:ntpython cdays-3-exercise-2.py cdays-3-test.txt' 26 else: 27 result = collect(open(sys.argv1, 'r') #調用collect函式,返回結果 28 for (right, lefts) in result.items(): #輸出結果 29 print "%d '%s't=>t%s" % (len(lefts), right, left

30、s) 30 o 運行截屏 3. 八皇后問題。在8*8的棋盤上,放置8個皇后,使得任兩個皇后不在同行同列同正負對角線上。 o 源代碼 Toggle line numbers 1 #coding:utf-8 2 '''cdays-3-exercise-3.py 3 note: 使用全局變量和函式的遞歸調用 4 ''' 5 6 global col #定義一些全局變量 7 global row 8 global pos_diag 9 global nag_diag 10 global count 11 12 def output(): 13 '

31、'' 輸出一種有效結果 14 ''' 15 global count 16 print row 17 count += 1 18 19 def do_queen(i): 20 ''' 生成所有正確解 21 param i: 皇后的數目 22 ''' 23 for j in range(0, 8): #依次嘗試07位置 24 if colj = 1 and pos_diagi-j+7 = 1 and nag_diagi+j = 1: #假設該行,正對角線,負對角線上都沒有皇后,那么放入i皇后 25 rowi

32、= j 26 colj = 0 #調整各個列表狀態 27 pos_diagi-j+7 = 0 28 nag_diagi+j = 0 29 if i < 7: 30 do_queen(i+1) #可遞增或遞減 31 else: 32 output() #產生一個結果,輸出 33 colj = 1 #恢復各個列表狀態為之前的 34 pos_diagi-j+7 = 1 35 nag_diagi+j = 1 36 37 if _name_ = '_main_': 38 col = #矩陣列的列表,存儲皇后所在列,假設該列沒有皇后,那么相應置為1,反之那么0 39 row = #矩

33、陣行的列表,存放每行皇后所在的列位置,隨著程序的執行,在不斷的變化中,之間輸出結果 40 pos_diag = #正對角線,i-j恒定,-707,并且b(i)+7統一到014 41 nag_diag = #負對角線,i+j恒定,014 42 count = 0 43 for index in range(0, 8): #一些初始化工作 44 col.append(1) 45 row.append(0) 46 for index in range(0, 15): 47 pos_diag.append(1) 48 nag_diag.append(1) 49 do_queen(0) #開始遞歸,先放

34、一個,依次遞增,反過來,從7開始遞減也可 50 print 'Totally have %d solutions!' % count 51 o 運行截屏 CDays-21. 在文中grep實現例子中,沒有考慮子目錄的處理,因為如果直接open目錄進行讀操作會出現錯誤,所以要求讀者修改這個例如代碼以便考慮到子目錄這種特殊情況,然后把最后探索出的 cdcGrep()嵌入 pycdc-v0.5.py 實現完成版本的 PyCDC。提示:子目錄處理,可以先判斷,如果是子目錄,就可以遞歸調用cdcGrep()函式。 o cdcGrep()函式的修改可以是 Toggle line numbe

35、rs 1 def cdcGrep(cdcpath,keyword): 2 '''光盤信息文本關鍵詞搜索函式 3 note: 使用最簡單的內置字串匹配處理來判定是否有關鍵詞包含 4 param cdcpath: 包含*.cdc 文件的目錄 5 param keyword: 搜索的關鍵詞 6 return: 組織匹配好的信息到字典中導出成 searched.dump 文件 7 todo: 可結合搜索引擎進行模糊搜索! 8 ''' 9 expDict = 10 filelist = os.listdir(cdcpath) # 搜索目錄中的文件 11 c

36、dcpath=cdcpath+"/" 12 for cdc in filelist: # 循環文件列表 13 if os.path.isdir(cdcpath+cdc): 14 cdcGrep(cdcpath+cdc,keyword) # 假設是子目錄,那么遞歸調用完成查找 15 else: 16 cdcfile = open(cdcpath+cdc) # 拼合文件路徑,并翻開文件 17 for line in cdcfile.readlines(): # 讀取文件每一行,并循環 18 if keyword in line: # 判定是否有關鍵詞在行中 19 #print

37、line # 打印輸出 20 expDictcdc.append(line) 21 #print expDict 22 pickle.dump(expDict,open("searched.dump","w") 23 o 源代碼 Toggle line numbers 1 # coding= utf-8 2 '''pycdc-v0.5.py 3 Lovely Python -2 PyDay 4 note: 將cdcGrep()嵌入 , 實現完成版本的 PyCDC 5 ''' 6 import sys, cm

38、d 7 from cdctools import * 8 class PyCDC(cmd d): 9 def _init_(self): 10 cmd d._init_(self) # initialize the base class 11 self.CDROM = '/media/cdrom0' 12 self.CDDIR = 'cdc/' 13 mpt="(PyCDC)>" 14 ro = '''PyCDC0.5 使用說明: 15 dir 目錄名 #指定保存和搜索目錄,默認是

39、 "cdc" 16 walk 文件名 #指定光盤信息文件名,使用 "*.cdc" 17 find 關鍵詞 #遍歷搜索目錄中所有.cdc文件,輸出含有關鍵詞的行 18 ? # 查詢 19 EOF # 退出系統,也可以使用Crtl+D(Unix)|Ctrl+Z(Dos/Windows) 20 ''' 21 22 def help_EOF(self): 23 print "退出程序 Quits the program" 24 def do_EOF(self, line): 25 sys.exit() 26 27 de

40、f help_walk(self): 28 print "掃描光盤內容 walk cd and export into *.cdc" 29 def do_walk(self, filename): 30 if filename = "":filename = raw_input("輸入cdc文件名: ") 31 print "掃描光盤內容保存到:'%s'" % filename 32 cdWalker(self.CDROM,self.CDDIR+filename) 33 34 def help_di

41、r(self): 35 print "指定保存/搜索目錄" 36 def do_dir(self, pathname): 37 if pathname = "": pathname = raw_input("輸入指定保存/搜索目錄: ") 38 self.CDDIR = pathname 39 print "指定保存/搜索目錄:'%s' ;默認是:'%s'" % (pathname,self.CDDIR) 40 41 def help_find(self): 42 print &qu

42、ot;搜索關鍵詞" 43 def do_find(self, keyword): 44 if keyword = "": keyword = raw_input("輸入搜索關鍵字: ") 45 print "搜索關鍵詞:'%s'" % keyword 46 cdcGrep(self.CDDIR,keyword) 47 48 if _name_ = '_main_': # this way the module can be 49 cdc = PyCDC() # imported by othe

43、r programs as well 50 cdc dloop() 51 2. 編寫一個類,實現簡單的棧。數據的操作按照先進后出(FILO)的順序。主要成員函式為put(item),實現數據item插入棧中;get(),實現從棧中取一個數據。 o 源代碼 Toggle line numbers 1 #coding:utf-8 2 '''cdays-2-exercise-2.py 自定義棧 3 note: 類和對象的使用 4 ''' 5 6 class MyStack(object): 7 '''MyStack 8 自定義棧

44、,主要操作有put(), get() and isEmpty() 9 ''' 10 def _init_(self, max): 11 ''' 12 初始棧頭指針和清空棧 13 param max: 指定棧的最大長度 14 ''' 15 self.head = -1 16 self.stack = list() 17 self.max = max 18 for i in range(self.max): 19 self.stack.append(0) 20 21 def put(self, item): 22 '&

45、#39;' 23 將item壓入棧中 24 param item: 所要入棧的項 25 ''' 26 if self.head >= self.max: #判斷當前棧是否滿了 27 return 'Put Error: The Stack is Overflow!' #提示棧溢出 28 else: 29 self.head += 1 #不滿,那么將item入棧,調整棧頂指針 30 self.stackself.head = item 31 print 'Put %s Success' % item 32 33 def get

46、(self): 34 ''' 35 獲得當前棧頂item 36 return: 棧頂item 37 ''' 38 if self.head < 0: #判斷當前棧是否為空 39 return 'Get Error: The Stack is Empty!' #提示棧空 40 else: 41 self.head -= 1 #出棧,返回棧頂元素,并調整棧頂指針 42 return self.stackself.head+1 43 44 def isEmpty(self): 45 ''' 46 獲得當前棧

47、的狀態,空或者非空 47 return: True(棧空) or False(棧非空) 48 ''' 49 if self.head < -1: 50 return True 51 return False 52 53 if _name_ = "_main_": 54 mystack = MyStack(100) 55 mystack.put('a') 56 mystack.put('b') 57 print mystack.get() 58 mystack.put('c') 59 print m

48、ystack.get() 60 print mystack.get() 61 print mystack.get() 62 o 運行截屏 CDays-11. 自動判定你自個兒或是朋友的Blog 是什么編碼的? o 源代碼 Toggle line numbers 1 #coding:utf-8 2 '''cdays-1-exercise-1.py 3 author: Ushengyan<mailto:shengyan1985gmail > 4 version:$Id$ 5 note: 使用chardet和 urllib2 6 see: chardet使用文檔:

49、 ://docs/, urllib2使用參考: ://lib/module-urllib2.html 7 ''' 8 9 import sys 10 import urllib2 11 import chardet 12 13 def blog_detect(blogurl): 14 ''' 15 檢測blog的編碼方式 16 param blogurl: 要檢測blog的url 17 ''' 18 try: 19 fp = urllib2.urlopen(blogurl) #嘗試翻開給定url 20 except Exception, e: #假設產生異常,那么給出相關提示并返回 21 print e 22 print 'download exception %s' % blogurl 23 return 0 24 blog = fp.read() #讀取內容 25 codedetect = chardet.detect(blog)"encoding"

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論