Python核心程式設計(第二版)課後習題部分答案
2-11:
借鑑了一位博主的稿子,但關鍵部分做了改動。
# !/usr/bin/env python # -*- coding:utf-8 -*- print ('Please input corresponding number to run different function:\n(1)Calculate the sum of five numbers;\n(2)Calculate the average of five numbers;\n(3)Exit') while True: total = 0 flag = int(input('Select:')) if flag==1: group = [] for i in range(5): group.append(int(input('Enter the %dth number:'%(i+1)))) for x in group: total += x print ('The SUM:%d'%total) elif flag==2: group = [] for i in range(5): group.append(float(input('Enter the %dth number:'%(i+1)))) for x in group: total += x average = total/5 print ('The average:%d'%average) elif flag==3: break else: print ('You have entered the wrong number, please try again.')
3-1:
Python是一門動態語言,也是一種強型別語言。它會根據你的賦值確定型別,在建立一個變數時開闢記憶體,而型別一旦確定就不再改變,當然,可以用工廠函式int()、float()來強制改變。
3-3:
因為__xxx__這樣的變數命名方式對Python有特殊意義,因為下劃線對直譯器有特殊意義,且是內建識別符號所使用的符號。(一般來講,_xxx 被看作是“私有的”)
3-4:
同一行可以書寫多條語句,不過語句之間要加';'加以間隔。
3-8:
書上有點小錯誤自己修正了一下,能夠在py檔案所在目錄下建立一個簡單的文字檔案,如果輸入的名字含有後綴的話(例如:.txt),生成的檔案就直接雙擊就可以打開了。
3-11:#! /usr/bin/env python 'makeTextFile.py -- create text file in current path' import os ls = os.linesep #字串給出當前平臺的行終止符 #get filename while True: fname = input('\nCreate a filename:')#書上沒有,我自己加上去的 if os.path.exists(fname): print("ERROR:'%s' aready exists"%fname) else: break #get file content (text) lines all = [] print("\nEnter lines('.' by itself to quit).\n") #loop until user terminates input while True: entry = input('請輸入一行文字>>>') if entry == '.': break else: all.append(entry) # write lines to file with proper line-ending fobj = open(fname, 'w') fobj.writelines(['%s%s'%(x,ls) for x in all]) #以行的單位寫入檔案 fobj.close() print ("Done.")
#! /usr/bin/env python 'raedTextFile.py -- raed and display text file' #get file fname = input("Please enter the filename you want to open:") #attempt to open file for reading try: fobj = open (fname,'r') except (IOError,e): print("*** file open error",e) else: #display contents to screen for eachline in fobj: print (eachline.rstrip())#截掉字串右邊的空格,split函式才是分割的 fobj.close()
4-1:
三個屬性:身份、型別、值;id,物件的記憶體地址;type,決定遵循什麼樣的規則操作;data,物件表示的資料項。
4-2:
物件不支援更新操作,值不可以改變,稱為immutable,不可更改的,Python中只有列表和字典型別是可變型別。
4-3:
字串、列表、元組是按順序訪問的,而字典是對映訪問的;一個是順序存放,順序訪問,一個是無序存放,通過唯一的鍵來訪問,稱雜湊鍵-值對。
4-5:
str()函式得到的字串可讀性好,而repr()函式得到的字串通常可以用來重新獲得該物件;repr()對Python比較友好,而str()對使用者比較友好。repr()和反引號(``)等價。
4-9:
Python僅快取簡單整型,因為他認為在程式中這些小整型會經常用到,現階段Python3.6快取的整型範圍為(-5,256),在這個範圍內,兩個物件的值相等,他們就是一個物件,即id相同,而字串也是不可變物件,只要指向相同的字元創,就是一個物件,只是有多個別名而已。
5-1:
標準整型:32位或64位;長整型:Python的長整型型別能表達的數值僅僅與你的機器支援的(虛擬)記憶體大小有關,Python能夠很輕鬆的表達很大的整型。
5-6:
只是涉及到兩個運算元的運算,想擴充套件實現多個運算元的運算,但是不行!
#coding:utf-8
""" 由於水平限制,只能實現2元運算"""
def calculator(expression):
operator = ['+','-','*','/']
sysmol = ''
for i in operator:
if i in expression:
sysmol = i
if sysmol == '':
print('操作符錯誤!')
return
num = expression.split(sysmol)
if '.' in num[0] or '.' in num[1]:
num1 = float(num[0])
num2 = float(num[1])
else:
num1 = int(num[0])
num2 = int(num[1])
if sysmol == operator[0]:
print (expression,'=',num1+num2)
elif sysmol == operator[1]:
print(expression,'=',num1-num2)
elif sysmol == operator[2]:
print(expression,'=',num1*num2)
elif sysmol == operator[3]:
print(expression,'=',num1/num2)
expression = input("Please input a math expression like'1+2':")
calculator(expression)
5-15:def gcd(x,y):
if x%y==0:
return y
else:
while True:
res = x%y
if res==0:
return y
break
elif res==1:
return 1
break
x=y
y=res
def lcm(x,y):
return x*y/(gcd(x,y)) #It helps me review the Number theroy. Suddenly be enlightened. Take a tumble. `~`
def main():
while True:
string = input ('Please input two numbers:')
num = string.split()
print ("Their min multiple is ", lcm(int(num[0]),int(num[1])))
print ("Their max factor is ", gcd(int(num[0]),int(num[1])))
prompt = input("Would do you like to quit?(yes/no):")
if prompt == "yes":
break
if __name__ == '__main__':
main()
6-2:
書上是Python2的語言,作者用的是Python3,所以做了一點改變,keyword模組中的keylist在Python3中沒有,而是換成了kwword,string.letters也變成了string.ascii_letters,同時也有print的差別。
#!usr/bin/env python3
import string
import keyword
alphas = string.ascii_letters + '_'
nums = string.digits
officalkey = keyword.kwlist
print ('Welcome to the Identifier Checker v1.0')
while True:
myInput= input('Identifier to test? (Press ctrl+C to exit)')
if myInput in officalkey:
print ("It's a offical Python identifier.")
elif len(myInput) > 1:
if myInput[0] not in alphas:
print ('''invalid: first symbol must be
alphabetic''')
else:
for otherChar in myInput[1:]:
if otherChar not in alphas + nums:
print ('''invalid: remaining
symbols must be alphanumeric''')
break
else:
print ("okay as an identifier")
elif len(myInput)==1 and myInput in alphas:
print ("It's a single indentifier.")
elif len(myInput)==1 and myInput in nums:
print ("Error!Not to be a number.")
6-3:
nums = [0,1,2,3,4,5,6,7,8,9]
string = input("請輸入一串數字:").split()
Tuple = []
for ch in string:
Tuple.append(int(ch))
res1 = sorted(Tuple)[::-1]
print (res1)
Dict = {}
for ch in string:
Dict[ch] = int(ch)
res2 = sorted(Dict)[::-1]
print (res2)
也是做了這一題之後,我才知道,Python有直接可以排序的函式sorted。
6-5:
分A,B,C,D四個函式,各實現每一小題。
#! /usr/bin/env python3.6
# __author__ =="spwpun" for python 6-5
import re
def testA():
string = input("Enter a string -->")
for i in range(len(string)):
print (string[i])
flag = input("Would do you like to see the previous character?")
if flag == 'yes':
print (string[i-1])
flag = input("Would do you like to see the later character?")
if flag == 'yes':
print (string[i+1])
def testB():
""" This function is to compare two strings. """
str1 = input("Please input your first string:")
str2 = input("Please input your second string:")
if len(str1) != len(str2):
print("They are not macth. They have different length.")
else:
for i in range(len(str1)):
if str1[i] != str2[i]:
print ("They are not matchs.")
break
elif i == (len(str1)-1):
print("They are matchs.")
def testC():
""" This function is to judge if a string is a palindrome. """
strC = input ("Enter a string -->")
long = len(strC)
if long%2 == 0:
for i in range(int(long/2)):
if strC[i] != strC[long-1-i]:
print ("Not repeat!")
break
else:
print ("Repeat!")
elif long%2 != 0:
for i in range(int(long/2)):
if strC[i] != strC[long-i-1]:
print ("Not repeat!")
break
else:
print("Repeat.")
def testD():
""" To get a palindrome. """
strd = input("Enter a string -->")
strd_ = strd[::-1]
strd = strd+strd_
print("The result is -->",strd)
if __name__ == "__main__":
choice = input("Please select test(A,B,C,D):")
if choice == 'A':
testA()
elif choice == 'B':
testB()
elif choice == 'C':
testC()
elif choice == 'D':
testD()
因為英文原版的C小題裡面就是讓判斷是否是迴文,翻譯成了重現,導致這道題耽誤了好長時間。這說明有能力的話還是儘量去看原版,翻譯的男面會有些紕漏。
6-6:
#! /usr/bin/env python3.6
# __author__ == "spwpun" for python 6-6
""" To define a function can replace string.strip()."""
def mystrip(string):
i=0;k=-1
while True:
if string[i] != ' ':
string = string[i:]
break
i = i+1
while True:
if string[k] != ' ':
string = string[:k+1]
break
k =k-1
return string
6-8:
將數字轉換成對應的英文單詞,列表的使用。
#!/usr/bin/env python
units = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve',
'thirteen','forteen','fifteen','sixteen','seventeen','eighteen','nineteen']
tens = ['twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
num_str = input("Please enter a number(0,999)-->")
num_int = int(num_str)
if num_int<=19:
print (units[num_int])
elif num_int<100:
ten = tens[int(num_str[0])-2]
unit = units[int(num_str[1])]
if unit == 'zero':
print (ten)
else:
print (ten+'-'+unit)
elif int(num_str[1:])<19:
hundred = units[int(num_str[0])]
rest = units[int(num_str[1:])]
print(hundred,' hundred ',rest)
else:
hund = units[int(num_str[0])]
ten = tens[int(num_str[1])-2]
uni = units[int(num_str[2])]
if uni == 'zero':
print(hund,' hundred ',ten)
else:
print(hund,' hundred ',ten+'-'+uni)
6-11:split和join的簡單用法。
#!/usr/bin/env python3.6
def mytransferIP(ipaddress):
blocks = []
length = len(ipaddress)
if length != 12:
print("Invalid IP address!")
else:
for i in range(4):
block = ipaddress[:3]
ipaddress = ipaddress[3:]
blocks.append(block)
return '.'.join(blocks)
def mytransferIP2(ipaddress):
if len(ipaddress) != 15:
print("Invalid IP address!")
trans = ipaddress.split('.')
ip = trans[0]+trans[1]+trans[2]+trans[3]
return ip
6-12:#!/usr/bin/env python3.6
# by spwpun
def findchr(string, char):
for i in range(len(string)):
if char == string[i]:
return i
else:
return -1
def rfindchr(string,char):
k = -1
while True:
if char == string[k]:
return k+len(string)
k -=1
if k+len(string)<0:
return -1
break
def subchr(string, origchr, newchar):
newst = []
newstr = ''
for i in range(len(string)):
newst.append(string[i])
if origchr == string[i]:
newst[i] = newchar
for i in range(len(newst)):
newstr += newst[i]
return newstr
要注意,字串是不可變物件,不能直接修改它的值,需要藉助list的可變性來建造一個newstr,newst是list,存放string,替換後通過迴圈新建一個newstr,不過這個newstr要事先定義為全域性變數,不然返回的時候會報錯。
7-1:
dict.update(dict2) 字典dict2的鍵-值對新增到dict中。
7-2:
數字,字串,元組是hashable的,可以做字典的鍵,但元組中的值要是不可變的,如數字、字串,而字典和list不是,不能作為字典的鍵。
7-3:
(a)用sorted函式;(b)迴圈顯示;
7-4:
list1 = ['a','b','c']
list2 = [1,2,3]
mydict = dict([ (list1[i],list2[i]) for i in range(len(list1)) ])