可愛的python習(xí)題答案_第1頁
可愛的python習(xí)題答案_第2頁
可愛的python習(xí)題答案_第3頁
可愛的python習(xí)題答案_第4頁
可愛的python習(xí)題答案_第5頁
已閱讀5頁,還剩37頁未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、可愛的python習(xí)題答案status 校對(duì) lizzie 完成度100% CDays-51. 計(jì)算今年是閏年嘛?判斷閏年條件, 滿足年份模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 #導(dǎo)入time模塊 7 thisyear = time.localtime()0 #獲取當(dāng)前年份 8 if thisyear % 400 = 0

2、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 運(yùn)行截屏 2. 利用python作為科學(xué)計(jì)算器。熟悉Python中的常用運(yùn)算符,并分別求出表達(dá)式12*34+78-132/6、(12*(34+78)-132)/6、(86/40)*5的值。并利用math模塊進(jìn)行數(shù)學(xué)計(jì)算,分別

3、求出145/23的余數(shù),0.5的sin和cos值(注意sin和cos中參數(shù)是弧度制表示)提醒:可通過import math; help(math)查看math幫助. o 源代碼 Toggle line numbers 1 #coding:utf-8 2 cdays-5-exercise-2.py 求表達(dá)式的值 3 note: 基本表達(dá)式運(yùn)算, 格式化輸出, math模塊 4 see: math模塊使用可參考/lib/module-math.html 5 6 7 x = 12*34+78-132/6 #表達(dá)式計(jì)算 8 y = (12*(34+78)-13

4、2)/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 #導(dǎo)入數(shù)學(xué)計(jì)算模塊 16 17 a = math.fmod(145, 23) #求余函式 18 b = math.sin(0.5) #正弦函式 19 c = math.cos(0.5) #余弦函式 20 21 print 145/23的余數(shù) = %d % a 22 print sin(0.5) = %f %b 23 p

5、rint cos(0.5) = %f %c 24 o 運(yùn)行截屏 3. 找出0100之間的所有素?cái)?shù)。 o 源代碼 Toggle line numbers 1 #coding:utf-8 2 cdays-5-exercise-3.py 求0100之間的所有素?cái)?shù) 3 note: for循環(huán), 列表類型 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):

6、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 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 運(yùn)行截屏 CDays-41. os 模塊中還有哪些功能可以使用? -

7、 提示使用 dir()和help() o os模塊中還有很多功能,主要的有以下些: os.error, os.path, os.popen, os.stat_result, os.sys, os.system等等等,詳細(xì)可參見dir(os)和Python幫助文檔help(os) 2. open() 還有哪些模式可以使用? o open()有以下幾種模式: r: 以只讀方式打開已存在文件,若文件不存在則拋出異常。此方式是默認(rèn)方式 U或者rU: Python慣例構(gòu)造了通用換行支持;提供U模式以文本方式打開一個(gè)文件,但是行可能隨時(shí)結(jié)束:Unix的結(jié)束符規(guī)定為n,蘋果系統(tǒng)則為r,還有Windows規(guī)定

8、為rn,所有這些規(guī)定在Python程序中統(tǒng)一為n. w: 以可寫方式打開存在或者不存在的文件,若文件不存在則先新建該文件,若文件存在則覆蓋該文件 a: 用于追加,對(duì)unix系統(tǒng)而言,所有的內(nèi)容都將追加到文件末尾而不管指針的當(dāng)前位置如何 b: 以二進(jìn)制方式打開。打開一個(gè)二進(jìn)制文件必須用該模式。增加b模式是用來兼容系統(tǒng)對(duì)當(dāng)二進(jìn)制和文本文件的處理不同 r+,w+和a+以更新方式打開文件(注意w+覆蓋文件) 3. 嘗試for . in .循環(huán)可以對(duì)哪些數(shù)據(jù)類型進(jìn)行操作? o for.in循環(huán)對(duì)于任何序列(列表,元組,字符串)都適用。但從廣義說來可以使用任何種類的由任何對(duì)象組成的序列 4. 格式化聲明,

9、還有哪些格式可以進(jìn)行約定? o 格式化申明 o 詳細(xì):/lib/typesseq-strings.html (精巧地址: http:/bit.ly/2TH7cF) d Signed integer decimal. i Signed integer decimal. o Unsigned octal. u Unsigned decimal. x Unsigned hexadecimal (lowercase). X Unsigned hexadecimal (uppercase). e Floating point exponential format

10、 (lowercase). E Floating point exponential format (uppercase). f Floating point decimal format. F Floating 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

11、 format if exponent is greater than -4 or less than precision, decimal format otherwise. 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 % ch

12、aracter in the result. 5. 現(xiàn)在的寫入文件模式好嘛? 有改進(jìn)的余地? o CDay-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 numb

13、ers 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要比+操作效率高。因?yàn)閷?duì)象的反復(fù)+,比一次性內(nèi)建處理,要浪費(fèi)更多的資源。 6. 讀取文件cdays-4-tes

14、t.txt內(nèi)容,去除空行和注釋行后,以行為單位進(jìn)行排序,并將結(jié)果輸出為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 cant stop;o Someone who makes you believe that there really is good

15、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 youre down,o and the world seems dark and empty,o Your forever friend lifts you up in spirits and makes that dark and empty worldo suddenly seem bright a

16、nd 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 forever friend holds your hand and tells you that everything is g

17、oing 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 = open(cdays-4-test.txt, r) #以讀方式打開文件 8 result = list() 9 for line in f.readlines(): #依次讀取每行

18、 10 line = line.strip() #去掉每行頭尾空白 11 if not len(line) or line.startswith(#): #判斷是否是空行或注釋行 12 continue #是的話,跳過不處理 13 result.append(line) #保存 14 result.sort() #排序結(jié)果 15 print result 16 open(cdays-4-result.txt, w).write(%s % n.join(result) #保存入結(jié)果文件 17 o 運(yùn)行截屏 CDays-31. 根據(jù)DiPy 10.6. 處理命令行參數(shù)(http:/www.wood

19、/diveintopython/scripts_and_streams/command_line_arguments.html 精巧地址:http:/bit.ly/1x5gMw)使用getopt.getopt()優(yōu)化當(dāng)前功能函式。 o 源代碼 Toggle line numbers 1 # coding=utf-8 2 Lovely Python -3 PyDay 3 PyCDC v0.3 4 see:/diveintopython/scripts_and_streams/command_line_argument

20、s.html 5 6 import os,sys 7 import getopt #導(dǎo)入getopt模塊 8 9 CDROM = /media/cdrom0 10 def cdWalker(cdrom,cdcfile): 11 export = 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

21、-exercise-1.py -d cdc -k 中國火 19 #搜索 cdc 目錄中的光盤信息,尋找有“中國火”字樣的文件或是目錄,在哪張光盤中 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, -h

22、elp): 34 usage() 35 sys.exit() 36 elif opt = -e: 37 #判別sys.argv2中是否有目錄,以便進(jìn)行自動(dòng)創(chuàng)建 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 #進(jìn)行文件搜索 47 2. 讀取某一簡單索引文件cdays-3-test.txt,其每行格式為文檔序號(hào) 關(guān)鍵詞,現(xiàn)需根據(jù)這些信息轉(zhuǎn)化為倒排索引

23、,即統(tǒng)計(jì)關(guān)鍵詞在哪些文檔中,格式如下:包含該關(guān)鍵詞的文檔數(shù) 關(guān)鍵詞 = 文檔序號(hào)。其中,原索引文件作為命令行參數(shù)傳入主程序,并設(shè)計(jì)一個(gè)collect函式統(tǒng)計(jì) 關(guān)鍵字序號(hào) 結(jié)果對(duì),最后在主程序中輸出結(jié)果至屏幕。 o cdays-3-test.txt 內(nèi)容:o 1 key1o 2 key2o 3 key1o 7 key3o 8 key2o 10 key1o 14 key2o 19 key4o 20 key130 key3o 源代碼 Toggle line numbers 1 #coding:utf-8 2 cdays-3-exercise-2.py 字典的使用 3 not: 使用sys.args,

24、 字典操作, 函式調(diào)用 4 see: sys模塊參見help(sys) 5 6 7 import sys #導(dǎo)入sys模塊 8 9 def collect(file): 10 改變 key-value對(duì)為value-key對(duì) 11 param file: 文件對(duì)象 12 return: 一個(gè)dict包含value-key對(duì) 13 14 result = 15 for line in file.readlines(): #依次讀取每行 16 left, right = line.split() #將一行以空格分割為左右兩部分 17 if result.has_key(right): #判斷是否已

25、經(jīng)含有right值對(duì)應(yīng)的key 18 resultright.append(left) #若有,直接添加到resultright的值列表 19 else: 20 resultright = left #沒有,則新建resultright的值列表 21 return result 22 23 if _name_ = _main_: 24 if len(sys.argv) = 1: #判斷參數(shù)個(gè)數(shù) 25 print usage:ntpython cdays-3-exercise-2.py cdays-3-test.txt 26 else: 27 result = collect(open(sys.

26、argv1, r) #調(diào)用collect函式,返回結(jié)果 28 for (right, lefts) in result.items(): #輸出結(jié)果 29 print %d %st=t%s % (len(lefts), right, lefts) 30 o 運(yùn)行截屏 3. 八皇后問題。在8*8的棋盤上,放置8個(gè)皇后,使得任兩個(gè)皇后不在同行同列同正負(fù)對(duì)角線上。 o 源代碼 Toggle line numbers 1 #coding:utf-8 2 cdays-3-exercise-3.py 3 note: 使用全局變量和函式的遞歸調(diào)用 4 5 6 global col #定義一些全局變量 7 g

27、lobal row 8 global pos_diag 9 global nag_diag 10 global count 11 12 def output(): 13 輸出一種有效結(jié)果 14 15 global count 16 print row 17 count += 1 18 19 def do_queen(i): 20 生成所有正確解 21 param i: 皇后的數(shù)目 22 23 for j in range(0, 8): #依次嘗試07位置 24 if colj = 1 and pos_diagi-j+7 = 1 and nag_diagi+j = 1: #若該行,正對(duì)角線,負(fù)對(duì)

28、角線上都沒有皇后,則放入i皇后 25 rowi = j 26 colj = 0 #調(diào)整各個(gè)列表狀態(tài) 27 pos_diagi-j+7 = 0 28 nag_diagi+j = 0 29 if i 14 ro = PyCDC0.5 使用說明: 15 dir 目錄名 #指定保存和搜索目錄,默認(rèn)是 cdc 16 walk 文件名 #指定光盤信息文件名,使用 *.cdc 17 find 關(guān)鍵詞 #遍歷搜索目錄中所有.cdc文件,輸出含有關(guān)鍵詞的行 18 ? # 查詢 19 EOF # 退出系統(tǒng),也可以使用Crtl+D(Unix)|Ctrl+Z(Dos/Windows) 20 21 22

29、 def help_EOF(self): 23 print 退出程序 Quits the program 24 def do_EOF(self, line): 25 sys.exit() 26 27 def help_walk(self): 28 print 掃描光盤內(nèi)容 walk cd and export into *.cdc 29 def do_walk(self, filename): 30 if filename = :filename = raw_input(輸入cdc文件名: ) 31 print 掃描光盤內(nèi)容保存到:%s % filename 32 cdWalker(self.

30、CDROM,self.CDDIR+filename) 33 34 def help_dir(self): 35 print 指定保存/搜索目錄 36 def do_dir(self, pathname): 37 if pathname = : pathname = raw_input(輸入指定保存/搜索目錄: ) 38 self.CDDIR = pathname 39 print 指定保存/搜索目錄:%s ;默認(rèn)是:%s % (pathname,self.CDDIR) 40 41 def help_find(self): 42 print 搜索關(guān)鍵詞 43 def do_find(self,

31、keyword): 44 if keyword = : keyword = raw_input(輸入搜索關(guān)鍵字: ) 45 print 搜索關(guān)鍵詞:%s % keyword 46 cdcGrep(self.CDDIR,keyword) 47 48 if _name_ = _main_: # this way the module can be 49 cdc = PyCDC() # imported by other programs as well 50 cdc.cmdloop() 51 2. 編寫一個(gè)類,實(shí)現(xiàn)簡單的棧。數(shù)據(jù)的操作按照先進(jìn)后出(FILO)的順序。主要成員函式為put(item)

32、,實(shí)現(xiàn)數(shù)據(jù)item插入棧中;get(),實(shí)現(xiàn)從棧中取一個(gè)數(shù)據(jù)。 o 源代碼 Toggle line numbers 1 #coding:utf-8 2 cdays-2-exercise-2.py 自定義棧 3 note: 類和對(duì)象的使用 4 5 6 class MyStack(object): 7 MyStack 8 自定義棧,主要操作有put(), get() and isEmpty() 9 10 def _init_(self, max): 11 12 初始棧頭指針和清空棧 13 param max: 指定棧的最大長度 14 15 self.head = -1 16 self.stack

33、= list() 17 self.max = max 18 for i in range(self.max): 19 self.stack.append(0) 20 21 def put(self, item): 22 23 將item壓入棧中 24 param item: 所要入棧的項(xiàng) 25 26 if self.head = self.max: #判斷當(dāng)前棧是否滿了 27 return Put Error: The Stack is Overflow! #提示棧溢出 28 else: 29 self.head += 1 #不滿,則將item入棧,調(diào)整棧頂指針 30 self.stackse

34、lf.head = item 31 print Put %s Success % item 32 33 def get(self): 34 35 獲得當(dāng)前棧頂item 36 return: 棧頂item 37 38 if self.head 0: #判斷當(dāng)前棧是否為空 39 return Get Error: The Stack is Empty! #提示???40 else: 41 self.head -= 1 #出棧,返回棧頂元素,并調(diào)整棧頂指針 42 return self.stackself.head+1 43 44 def isEmpty(self): 45 46 獲得當(dāng)前棧的狀態(tài),

35、空或者非空 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 mystack.get() 60 print mystack.get() 61 print mystack.get() 62 o 運(yùn)行截

36、屏 CDays-11. 自動(dòng)判定你自個(gè)兒或是朋友的Blog 是什么編碼的? o 源代碼 Toggle line numbers 1 #coding:utf-8 2 cdays-1-exercise-1.py 3 author: Ushengyan 4 version:$Id$ 5 note: 使用chardet和 urllib2 6 see: chardet使用文檔: /docs/, urllib2使用參考: /lib/module-urllib2.html 7 8 9 import sys 10

37、 import urllib2 11 import chardet 12 13 def blog_detect(blogurl): 14 15 檢測(cè)blog的編碼方式 16 param blogurl: 要檢測(cè)blog的url 17 18 try: 19 fp = urllib2.urlopen(blogurl) #嘗試打開給定url 20 except Exception, e: #若產(chǎn)生異常,則給出相關(guān)提示并返回 21 print e 22 print download exception %s % blogurl 23 return 0 24 blog = fp.read() #讀取內(nèi)容 25 codedetect = chardet.detect(blog)encoding #檢測(cè)得到編碼方式 26 print %st-t%s % (blogurl, codedetect) 27 fp.close() #關(guān)閉 28 return 1 29 30 if _name_ = _main_: 31 if len(sys.argv) = 1: 32 print usage:ntpy

溫馨提示

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

評(píng)論

0/150

提交評(píng)論