Python 核心程式設計第七章練習題
7–1. 字典方法。哪個字典方法可以用來把兩個字典合併到一起? update
def updateDict():
dict1 = {'name': 'John', 'Age': 20}
dict2 = {'address': 'Beijing road'}
dict1.update(dict2)
print(dict1)
7–3. 字典和列表的方法。
(a) 建立一個字典,並把這個字典中的鍵按照字母順序顯示出來。 sorted(dict1)
def sortDict(): dict1 = {'name': 'John', 'age': 20} print(sorted(dict1))
(b) 現在根據已按照字母順序排序好的鍵,顯示出這個字典中的鍵和值。
def sortDict():
dict1 = {'name': 'John', 'age': 20}
sort_dict1 = sorted(dict1.items(), key = lambda dict1:dict1[0])
print(sort_dict1)
(c)同(b),但這次是根據已按照字母順序排序好的字典的值,顯示出這個字典中的鍵和值。(注
意:對字典和雜湊表來說,這樣做一般沒有什麼實際意義,因為大多數訪問和排序(如果需要)都是
基於字典的鍵,這裡只把它作為一個練習。)
def sortDict(): dict1 = {'name': 'John', 'age': '20', 'num': '10'} value_sort_dict1 = sorted(dict1.items(), key = lambda dict1:dict1[1]) print(value_sort_dict1)
7-4. 建立字典。給定兩個長度相同的列表,比如說,列表[1, 2, 3,...]和['abc', 'def','ghi',...],用這兩個列表裡的所有資料組成一個字典,像這樣:{1:'abc', 2: 'def', 3: 'ghi',...}
def listToDict():
list1 = [1, 2, 3]
list2 = ['abc', 'def','ghi']
dict1 = dict(zip(list1,list2))
print(dict1)
7–5. userpw2.py. 下面的問題和例題7.1 中管理名字-密碼的鍵值對資料的程式有關。
(a)修改那個指令碼,使它能記錄使用者上次的登入日期和時間(用time 模組),並與使用者密碼一起
儲存起來。程式的介面有要求使用者輸入使用者名稱和密碼的提示。無論戶名是否成功登入,都應有提示,
在戶名成功登入後,應更新相應使用者的上次登入時間戳。如果本次登入與上次登入在時間上相差不
超過4 個小時,則通知該使用者: “You already logged in at: <last_ login_timestamp>.”
(b) 新增一個“管理”選單,其中有以下兩項:(1)刪除一個使用者 (2)顯示系統中所有使用者的名
字和他們的密碼的清單。
(c) 口令目前沒有加密。請新增一段對口令加密的程式碼(請參考crypt, rotor, 或其它加密模組)
(d) 為程式新增圖形介面,例如,用Tkinter 寫。
(e) 要求使用者名稱不區分大小寫。
(f) 加強對使用者名稱的限制,不允許符號和空白符。
(g)合併“新使用者”和“老使用者”兩個選項。如果一個新使用者試圖用一個不存在的使用者名稱登入,
詢問該使用者是否是新使用者,如果回答是肯定的,就建立該帳戶。否則,按照老使用者的方式登入。
7-6. 列表和字典。建立一個簡單的股票證券投資資料系統。其中應至少包含四項資料:股市
行情顯示器符號,所持有的股票,購買價格及當前價位 - 你可以隨意新增其他資料項,比如收益率,
52 周最高指數、最低指數,等等。
使用者每次輸入各列的資料構成一個輸出行。每行資料構成一個列表。還有一個總列表,包括了
所有行的資料。資料輸入完畢後,提示使用者選擇一列資料項進行排序。把該資料項抽取出來作為字
典的鍵,字典的值就是該鍵對應行的值的列表。提醒讀者:被選擇用來排序的資料項必須是非重複
的鍵,否則就會丟失資料,因為字典不允許一個鍵有多個值。
你還可以選擇其他計算輸出,比如,盈虧比率,目前證券資產價值等。
7-7. 顛倒字典中的鍵和值。用一個字典做輸入,輸出另一個字典,用前者的鍵做值,前者的值做鍵.
def keyToValue():
d1 = {'name': 'John', 'age': 20, 'num': 10}
d2 = {}
for key in d1:
v = d1.get(key)
d2[v] = key
print(d2)
7-8. 人力資源。建立一個簡單的僱員姓名和編號的程式。讓使用者輸入一組僱員姓名和編號。
你的程式可以提供按照姓名排序輸出的功能,僱員姓名顯示在前面,後面是對應的僱員編號。附加
題:新增一項功能,按照僱員編號的順序輸出資料。
def systemHR():
print('please input the 3 employee name and number:')
i = 0
name = []
number = []
while i < 3:
na,no = str(input()).split()
name.append(na)
number.append(int(no))
i += 1
#print(name)
dictHR = dict(zip(name,number))
sortName = sorted(dictHR)
print('the result is :')
for i in sortName:
print('%s %s' %(i, dictHR[i]))
7-9. 翻譯
(a) 編寫一個字元翻譯程式(功能類似於Unix 中的tr 命令)。我們將這個函式叫做tr(),它有
三個字串做引數: 源字串、目的字串、基本字串,語法定義如下:
def tr(srcstr, dststr, string)
srcstr 的內容是你打算“翻譯”的字元集合,dsrstr 是翻譯後得到的字元集合,而string 是
你打算進行翻譯操作的字串。舉例來說,如果srcstr == 'abc', dststr == 'mno', string ==
'abcdef', 那麼tr()的輸出將是'mnodef'. 注意這裡len(srcstr) == len(dststr).
在這個練習裡,你可以使用內建函式chr() 和 ord(), 但它們並不一定是解決這個問題所必不
可少的函式。
def tr(srcstr, dststr, string):
count = string.count(srcstr)
print(count)
if count > 0:
for i in range(1,count+1):
id = string.index(srcstr)
le = len(srcstr)
string = string[:id]+ dststr + string[id+le:]
print(string)
或者用 replace 方法:
def tr(srcstr, dststr, string):
count = string.count(srcstr)
print(count)
if count > 0:
string = string.replace(srcstr,dststr)
print(string)
else:
print(string)
tr('mor','eve','good morning morning')
(b) 在這個函式裡增加一個標誌符引數,來處理不區分大小寫的翻譯問題。
def tr(srcstr, dststr, string, case = 1):
if case == 1:
count = string.count(srcstr)
print(count)
if count > 0:
string = string.replace(srcstr,dststr)
print(string)
else:
print(string)
else:
srcstr = srcstr.lower()
string = string.lower()
count = string.count(srcstr)
print(count)
if count > 0:
string = string.replace(srcstr,dststr)
print(string)
else:
print(string)
tr('mor','eve','good morning Morning',0)
(c)修改你的程式,使它能夠處理刪除字元的操作。字串srcstr 中不能夠對映到字串dststr
中字元的多餘字元都將被過濾掉。換句話說,這些字元沒有對映到dststr 字串中的任何字元,因
此就從函式返回的字元裡被過濾掉了。舉例來說:如果 srcstr == 'abcdef', dststr == 'mno',
string == 'abcdefghi', 那麼tr()將輸出'mnoghi'. 注意這裡len(srcstr) >= len(dststr).
def tre(srcstr, dststr, string):
count = string.count(srcstr)
print(count)
if count > 0:
string = string.replace(srcstr,dststr)
print(string)
else:
print(string)
tre('morning','eve','good morning morning')
7–10. 加密。
(a) 用上一個練習的思路編寫一個"rot13"翻譯器。"rot13"是一個古老而又簡單的加密方法,
它把字母表中的每個字母用其後的第13 個字母來代替。字母表中前半部分字母將被對映到後半部分,
而後半部分字母將被對映到前半部分,大小寫保持不變。舉例來說,'a'將被替換為'n','X'將被替
換為'K'; 數字和符號不進行翻譯。
(b)在你的解決方案的基礎上加一個應用程式,讓它提示使用者輸入準備加密的字串(這個演算法
同時也可以對加密後的字串進行解密),如下所示:
% rot13.py
Enter string to rot13: This is a short sentence. Your string to en/decrypt was: [This
is a short sentence.].
The rot13 string is: [Guvf vf n fubeg fragrapr.].
%
% rot13.py
Enter string to rot13: Guvf vf n fubeg fragrapr. Your string to en/decrypt was: [Guvf
vf n fubeg fragrapr.].
The rot13 string is: [This is a short sentence.].
def rot13(string):
'''''
將一個字串變為rot13加密
'''
lens=len(string)
newstring=''
for i in range(0,lens):
if 64<ord(string[i])<78 or 96<ord(string[i])<110:
newstring=newstring+chr(ord(string[i])+13)
elif 91>ord(string[i])>77 or 123>ord(string[i])>109:
newstring=newstring+chr(ord(string[i])-13)
else:
newstring=newstring+string[i]
print(newstring)
rot13('Guvf vf n fubeg fragrapr')