8–2. 迴圈.
編寫一個程式, 讓使用者輸入三個數字: (f)rom, (t)o, 和 (i)ncrement . 以 i為步長, 從 f 計數到 t , 包括 f 和 t . 例如, 如果輸入的是 f == 2, t == 26, i == 4 , 程式將輸出 2, 6, 10, 14, 18, 22, 26.
x,y,z=raw_input('pls input 3 numbers separated by comma:').split(',')f=int(x)t=int(y)i=int(z)while f<=t: print f, f+=i
8–4. 素數.
我們在本章已經給出了一些代碼來確定一個數位最大約數或者它是否是一個素數. 請把相關代碼轉換為一個傳回值為布爾值的函數,函數名為 isprime() . 如果輸入的是一個素數, 那麼返回 True , 否則返回 False .
<pre name="code" class="python">def isprime(num): if num==1: return False count=num/2 while count>1: if num%count==0: return False break count-=1 else: return Truefor eachnum in range(10,21): print eachnum,'is prime',isprime(eachnum)
8–5. 約數. 完成一個名為 getfactors() 的函數. 它接受一個整數作為參數, 返回它所有約數的列表, 包括 1 和它本身,
def getfactors(num): factors=[] count=num/2 while count>=1: if num%count==0: factors.append(count) count-=1 factors.append(num) return factorsprint getfactors(10)
8–6. 素因子分解.
以剛才練習中的 isprime() 和 getfactors() 函數為基礎編寫一個函數, 它接受一個整數作為參數, 返回該整數所有素數因子的列表. 這個過程叫做求素因子分解, 它輸出的所有因子之積應該是原來的數字. 注意列表裡可能有重複的元素. 例如輸入 20 , 返回結果應該是 [2, 2, 5] .
def isprime(num): if num==1: return False count=num/2 while count>1: if num%count==0: return False break count-=1 else: return Truedef getfactors(num): factors=[] count=num/2 while count>1: if isprime(count) and num%count==0: factors.append(count) num=num/count count=num/2 else: count-=1 if num != 1: factors.append(num) return factorsprint getfactors(20)
8–7. 全數.
完全數被定義為這樣的數字: 它的約數(不包括它自己)之和為它本身. 例如: 6的約數是 1, 2, 3, 因為 1 + 2 + 3 = 6 , 所以 6 被認為是一個完全數. 編寫一個名為 isperfect()的函數, 它接受一個整數作為參數, 如果這個數字是完全數, 返回 1 ; 否則返回 0 .
def isperfect(num): factors=[] count=num/2 while count>=1: if num%count==0: factors.append(count) count-=1 if sum(factors)==num: return 1 else: return 0print isperfect(6)
8–8. 階乘.
一個數的階乘被定義為從 1 到該數字所有數位乘積. N 的階乘簡寫為 N! .寫一個函數, 指定N, 返回 N! 的值.
def factorial(n): if 0==n: return 1 product=1 for i in range(1,n+1): product*=i return productprint factorial(5)
8–9. Fibonacci 數列.
Fibonacci 數列形如 1, 1, 2, 3, 5, 8, 13, 21, 等等. 也就是說,下一個值是序列中前兩個值之和. 寫一個函數, 給定 N , 返回第 N 個 Fibonacci 數字. 例如, 第1 個 Fibonacci 數字是 1 , 第 6 個是 8 .
def f(n): flist=[0,1,1] sum=0 if 1==n or 2==n: return 1 else: for i in range (2,n): flist.append(flist[i]+flist[i-1]) return flist[n]print f(6)
8–10. 文本處理.
統計一句話中的母音, 輔音以及單詞(以空格分割)的個數. 忽略母音和輔音的特殊情況, 如 "h", "y", "qu" 等. 附加題: 編寫處理這些特殊情況的代碼.
vowels=set('aeiouAEIOU')letters=set([chr(i) for i in range(97,123)]+[chr(i) for i in range(65,91)])constants=letters-vowelssentence="And the lord spake, saying: First shalt thou take out the Holy Pin."print sentenceprint 'how many words in above str %d' %len([word for word in sentence.split()])print 'how many vowels in above str %d' %len([letter for letter in sentence if letter in vowels])print 'how many constants in above str %d' %len([letter for letter in sentence if letter in constants])
8–11. 文本處理.
要求輸入一個姓名列表,輸入格式是“Last Name, First Name,” 即 姓,逗號, 名. 編寫程式處理輸入, 如果使用者輸入錯誤, 比如“First Name Last Name,” , 請糾正這些錯誤, 並通知使用者. 同時你還需要記錄輸入錯誤次數. 當使用者輸入結束後, 給列表排序, 然後以“姓 , 名" 的順序顯示.
輸入輸出樣本(你不需要完全按照這裡裡例子完成):
% nametrack.py
Enter total number of names: 5
Please enter name 0: Smith, Joe
Please enter name 1: Mary Wong
>> Wrong format... should be Last, First.
>> You have done this 1 time(s) already. Fixing input... Please enter name 2: Hamilton,
Gerald
Please enter name 3: Royce, Linda
Please enter name 4: Winston Salem
>> Wrong format... should be Last, First.
>> You have done this 2 time(s) already. Fixing input...
The sorted list (by last name) is:
Hamilton, Gerald
Royce, Linda
Salem, Winston
Smith, Joe
Wong, Mary
nums=int(raw_input('Enter total number of names: '))namelist=[]errs=0for i in range(5): tmp=raw_input('pls enter name %d:' %i) if ',' not in tmp: errs+=1 print 'wrong format...should be Last,First.' print 'you have done this %d time(s) already. Fixing input' %errs tmp=tmp.split(' ')[1]+','+tmp.split(' ')[0] namelist.append(tmp) else: namelist.append(tmp)namelist.sort()print 'The sorted list (by last name) is:'for i in namelist: print i
8–12. (整數)位操作.
編寫一個程式, 使用者給出起始和結束數字後給出一個下面這樣的表格,分別顯示出兩個數字間所有整數的十進位, 二進位, 八進位和十六進位表示. 如果字元是可列印的ASCII 字元, 也要把它列印出來, 如果沒有一個是可列印字元, 就省略掉 ASCII 那一欄的表頭.
start=int(raw_input('pls input a start number:'))end=int(raw_input('pls input a end number:'))title='DEC\tBIN\tOCT\tHEX'for i in range(start,end+1): if 32<=i<=126: title+='\tASCII' breakprint titlefor i in range(start,end+1): if 32<=i<=126: print '%d\t%07d\t%o\t%x\t%s' %(i,int(bin(i)[2:]),i,i,chr(i)) else: print '%d\t%07d\t%o\t%x' %(i,int(bin(i)[2:]),i,i)