python核心編程第七章練習

7-3(a)

dic = {'Jack': 'man', 'Amy': 'woman', 'Lorry': 'woman', 'Json': 'man'}
print sorted(dic)

7-3(b)

dic = {'Jack': 'man', 'Amy': 'woman', 'Lorry': 'woman', 'Json': 'man'}
for key in sorted(dic):
	print 'key:%s, value:%s'%(key, dic[key])

7-3(c)

#!/user/bin/env python
# -*- coding:utf-8 -*-

dic = {'Jack': 'man', 'Amy': 'woman', 'Lorry': 'woman', 'Json': 'man'}
# 先用dic.items()函數返回一個鍵值對的列表,就是先把字典轉換成列表,然後用lambda函數把列表中的第二個值賦予給key
# 所以還是對key進行排序,只是key被賦予了value的值
for key, value in sorted(dic.items(), key=lambda x:x[1]):
	print 'key:%s, value:%s'%(key, dic[key])

print dic.items()

7-4

#!/user/bin/env python
# -*- coding:utf-8 -*-

list1 = ['Jack', 'Amy', 'Jane', 'Lorry']
list2 = ['China', 'US', 'UK', 'Japan']

dic = zip(list1, list2)
print dic

7-5

#!/user/bin/env python
# -*- coding:utf-8 -*-
from Tkinter import *
import time, getpass, hashlib, tkMessageBox


db = {}


class Reg(Frame):
    def __init__(self, master): # 原來showmenue頁面
        self.frame = Frame(master)
        self.frame.pack() 
        self.bottomframe = Frame(master)
        self.bottomframe.pack(side = BOTTOM)
        
        registerbutton = Button(self.frame, text="User", fg="blue", command = self.users)
        registerbutton.pack(side = LEFT)

        managebutton = Button(self.frame, text="Manage", fg="black", command = self.manage)
        managebutton.pack(side = LEFT)

        quitbutton = Button(self.bottomframe, text="Quit", fg="red", command = self.frame.quit)
        quitbutton.pack(side = BOTTOM)

    def users(self):
        self.second = Tk()
        self.frame = Frame(self.second, padx=50, pady=50) 
        self.frame.pack() 
        lab1 = Label(self.frame,text = "Username:")
        lab1.grid(row = 0, column = 0, sticky = W)
        self.ent1 = Entry(self.frame)
        self.ent1.grid(row = 0, column = 1, sticky = W)

        lab2 = Label(self.frame, text = "Password:")
        lab2.grid(row = 1, column = 0)
        self.ent2 = Entry(self.frame, show = "*")
        self.ent2.grid(row = 1, column = 1, sticky = W)

        button = Button(self.frame, text = "Signup", command = self.Signup)
        button.grid(row = 2, column = 2, sticky = W)
        button = Button(self.frame, text = "Login", command = self.Login)
        button.grid(row = 2, column = 3, sticky = W)

        button2 = Button(self.frame, text = "Quit", fg="red", command = frame.quit)
        button2.grid(row = 3, column = 3, sticky = W)
        
    # 驗證註冊賬號
    def Signup(self):
        # 引入用戶
        user = self.ent1.get().lower()
        # 如果數據庫中已經有了賬號,提示重新輸入
        if db.has_key(user):
            tkMessageBox.showwarning('Signup', 'Username taken try another!')
            
        elif not user.isalnum() or ' ' in user:
            tkMessageBox.showerror('Signup', 'invlid username!')
                
        else:
            # 輸入密碼
            tkMessageBox.showinfo('Signup', 'You have already signup.')
            psw = self.ent2.get()
            # 把賬號和密碼加入數據庫中
            timeNow = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            db[user] = hashlib.md5(psw).hexdigest(),timeNow

    # 驗證登錄賬號
    def Login(self):
        user = self.ent1.get().lower()
        psw = self.ent2.get()
        if db.has_key(user) and db.get(user)[0] == hashlib.md5(psw).hexdigest():
            timeNow = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            db[user] = hashlib.md5(psw).hexdigest(),timeNow
            diffTime = float(time.time() - time.mktime(time.strptime(db[user][1],'%Y-%m-%d %H:%M:%S'))) / 3600
            if diffTime <= 4:
                tkMessageBox.showinfo('Login','Welcome, %s!You already logged in at:%s'% (user,db[user][1]))
                
        else:
            tkMessageBox.showerror('Login', 'invlid username!')

    # 管理界面
    def manage(self):
        second = Tk()
        frame = Frame(second, padx=50, pady=50) 
        frame.pack()  

        button = Button(frame, text = "Delete a User", fg='red', command = self.dele)
        button.grid(row = 1, column = 0, sticky = W)

        button = Button(frame, text = "Show all users", command = self.showusers)
        button.grid(row = 1, column = 1, sticky = W)

    # 刪除用戶界面
    def dele(self):
        self.third = Tk()
        self.frame_dele = Frame(self.third)
        self.frame_dele.pack()  

        lab1 = Label(self.frame_dele,text = "Username:")
        lab1.grid(row = 0, column = 0, sticky = W)
        self.ent1 = Entry(self.frame_dele)
        self.ent1.grid(row = 0, column = 1, sticky = W)

        button = Button(self.frame_dele, text = "Submit", command = self.dele_user)
        button.grid(row = 1, column = 2, sticky = W)

    # 執行刪除命令
    def dele_user(self):
        username = self.ent1.get()
        if db.has_key(username):
            del db[username]
            tkMessageBox.showinfo('Dele', '%s has been removed!'%username)
        else:
            tkMessageBox.showwarning('Dele', 'username is not existing!')
        des = self.frame_dele.destroy()
        

    def showusers(self):
        third = Tk()
        frame = Frame(third)
        frame.pack()
        username_arr = []
        for username in db:
            username_arr.append(username)

        lab = Label(frame, text = username_arr)
        lab.grid(row = 0, column = 0, sticky = W)


root = Tk()
frame = Frame(root)
if __name__ == '__main__':
    app = Reg(root)
root.mainloop()

7-7

dic1 = {'mike':'China', 'jane':'Japan', 'dony':'Italy'}

dic2 = dict.fromkeys(dic1.values())

for key in dic1:
	dic2[dic1[key]] = key

print dic1
print dic2

7-8

db = {'mike':'1', 'jane':'3', 'dony':'2'}
dic_sorted = {}
dic = {}

done = False 
while not done:
	employeename = raw_input('>Name: ').strip().lower()
	identifier = raw_input('>id: ').strip()
	next = raw_input('>next one? enter no to end.').strip()
	db[employeename] = identifier
	if next == 'no':
		done = True
	
print 'sorted by name.'
for key in sorted(db):
	print 'name:%s, id:%s'%(key, db[key])

for key in db:
	dic[db[key]] = key

print 'sorted by id.'
for key in sorted(dic):
	print 'name:%s, id:%s'%(dic[key], key)

7-9

def tr(stcstr, dststr, string, sensitive = True):
	if sensitive is False:
		stcstr, dststr, string = stcstr.lower(), dststr.lower(), string.lower()
	lens = len(stcstr)
	index = string.find(stcstr)
	if index > -1:
		string = string[0:index] + dststr + string[index+lens:]

	return string

print tr('abc', 'mof', 'abcefg')
print tr('bcd', 'mof', 'abcdefg')
print tr('abcdef', 'mon', 'abcdefghi')

7-10

import string


def rot13():
    scrstr = raw_input('Enter string to rot13: ')
    print 'Your string to en/decrypt was: ', scrstr
    cyptstr = []
    for s in scrstr:
        if s in string.letters:
            if ord(s) >= 97 and ord(s) + 13 > 122:
                s = chr(ord(s) - 13)
            elif ord(s) <= 90 and ord(s) + 13 > 90:
                s = chr(ord(s) - 13)
            else:
                s = chr(ord(s) + 13)
        cyptstr.append(s)

    return 'The rot13 string is: ' + ''.join(cyptstr)

print rot13()

7-13

import random



def check_set():
    A = set()
    B = set()
    
    for N in range(10):
        n = random.randint(0, 9)
        A.add(n)

    for i in range(10):
        n = random.randint(0, 9)
        B.add(n)

    for i in range(3):
        print 'A is:%s\nB is:%s\nPlease input A|B and A&B.' %(sorted(A), sorted(B))
        intersection = set(map(int,raw_input('Please input A&B:').split()))
        union = set(map(int,raw_input('Please input A|B:').split()))

        print 'You input:\nintersection:%s\nunion:%s'%(intersection,union)
        if intersection == A&B and union == A|B:
            return 'confirmed!'
            break
        elif i==2:
            return 'A&B:%s\nA|B:%s'%(A&B, A|B)
            
print check_set()

7-15

def C_set():  
    Aset = set(raw_input('Please input A set:').split())  
    Bset = set(raw_input('Please input B set:').split())  
    op = raw_input('Please input Operator:')  
    if op=='in':  
        print Aset in Bset  
    elif op=='not in':  
        print Aset not in Bset  
    elif op=='&':  
        print Aset & Bset  
    elif op==r'|':  
        print Aset | Bset  
    elif op=='<':  
        print Aset<Bset  
    elif op=='>':  
        print Aset>Bset  
    elif op=='=':  
        print Aset==Bset  
    elif op=='!=':  
        print Aset!=Bset  
          
if __name__=='__main__':  
    C_set() 




發佈了30 篇原創文章 · 獲贊 7 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章