Python核心编程 第七章练习

7_3

#!/usr/bin/env python
# encoding: utf-8

if __name__ == "__main__":
    dct = dict(zip(["emxample", "port"], ['7_3', 80]))
    sorted_dct = sorted(dct)
    print sorted_dct
    print "the sorted keys and values are: "
    for i in sorted(dct):
        print "the key %s is %s" %(i, dct[i])

7_4

这道题无非就是考察一下zip函数的使用,越发觉得python的zip函数功能强大了

#!/usr/bin/env python
# encoding: utf-8

lst1 = range(1, 4)
lst2 = ['abc', 'def', 'ghi']
print "list1 is %s, list 2 is %s" %(lst1, lst2)
dct = dict(zip(lst1, lst2))
print "the dict is %s" %dct

7_5

这个地方我花了比较久的时间,因为需要摸一边Tkinter的功能,我博主是第一次在python上接触GUI的操作,想想还有点小激动呢。
Tkinter的教程我找到的都不算很全,google了几篇文章,基本上是教授基本功能的,本来想通过几个窗口的调用来实现这个功能,后来发觉这个地方用力过猛,反而不是正道,于是就用窗口加命令行的方式暂且实现了这个题目的要求(为了找理由我也是蛮拼)。关于Tkinter的介绍我参考的是廖雪峰的python教程。链接: http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0013868326118089581a091a04e4c30b2b7896392bdde5c000

#!/usr/bin/env python
# encoding: utf-8

import datetime, crypt, tkMessageBox, string
from Tkinter import *

db = {}
def newuser(name, pwd):
    prompt = 'login desired: '
    availableChar = string.lowercase + string.uppercase
    while True:
        bNotAvail = False
        if name in db:
            prompt = 'name taken, try another: '
            continue
        for i in name:
            if i not in availableChar:
                prompt = 'name not available, try another: '
                bNotAvail = True
                break
        if bNotAvail:
            continue
        break
    tme = datetime.datetime.now()
    cryptpwd = crypt.crypt(pwd, name)
    db[name] = [cryptpwd, tme]

def olduser(name, pwd):
    lst = db.get(name)
    if lst:
        passwd = lst[0]
        timeOflst = lst[1]
        tme = datetime.datetime.now()
        cryptpwd = crypt.crypt(pwd, name)
        if passwd == cryptpwd:
            print 'welcome back', name
            timedelta = tme - timeOflst
            if timedelta.total_seconds()/3600 < 4:
                print "You already logged in at: %s" %tme.strftime("%Y/%m/%d %X")
            lst[1] = tme
            return
    print 'login incorrect'

def loginuser():
    name = raw_input('login: ')
    pwd = raw_input('passwd: ')
    if name not in db:
        isNew = raw_input("Are you a new user:(Y/N) ").split()[0].lower()
        if isNew == 'y':
            newuser(name, pwd)
    olduser(name, pwd)


def showuser():
    print "the list of user : password is: "
    for i in db:
        print "%s : %s" %(i, db[i])

def deleteuser():
    user = raw_input("input a user to delete: ")
    if user in db:
        del db[user]
    else:
        print "the user doesn't exist!"

class Application(Frame):
    def __init__(self, master = None):
        self.master = Tk()
        self.master.title('Login System')
        self.master.geometry('400x200')
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.signButton = Button(self, text = 'User Login',
                                 command = loginuser)
        self.signButton.pack()
        self.showButton = Button(self, text = 'Show all users',
                                 command = showuser)
        self.showButton.pack()
        self.deleteButton = Button(self, text = 'Detete user',
                                 command = deleteuser)
        self.deleteButton.pack()
        self.quitButton = Button(self, text = 'Quit',
                                 command = self.quit)
        self.quitButton.pack()

if __name__ == "__main__":
    app = Application()
    app.mainloop()

7_6

恩,刚刚学会简单的Txinter,拿出来显摆一下才不至于忘记。

#!/usr/bin/env python
# encoding: utf-8

from Tkinter import *

stock = dict()

def AddStock():
    pr = "type the stock, share, purchase price, current price: \n"
    messagelst = raw_input(pr).strip().split()
    stockName = messagelst[0]
    del messagelst[0]
    stock[stockName] = messagelst

def ShowStock():
    sortedkey = sorted(stock)
    for i in sortedkey:
        print i, ' : ', stock[i]

class Application(Frame):
    def __init__(self, master = None):
        self.master = Tk()
        self.master.title('Stock System')
        self.master.geometry('400x200')
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.addBtn = Button(self, text = "Add stock",
                             command = AddStock)
        self.showBtn = Button(self, text = "Show stock",
                              command = ShowStock)
        self.quitBtn = Button(self, text = "Quit",
                              command = self.quit)
        self.addBtn.pack()
        self.showBtn.pack()
        self.quitBtn.pack()

if __name__ == '__main__':
    app = Application()
    app = mainloop()

7_7

用zip就是这么自信。

#!/usr/bin/env python
# encoding: utf-8

if __name__ == "__main__":
    dct1 = dict(([1, 10], [2, 20], [3, 30], [4, 40], [5, 50], [6, 60]))
    print dct1
    dct2 = dict(zip(dct1.values(), dct1.keys()))
    print dct2

7_8

#!/usr/bin/env python
# encoding: utf-8

from Tkinter import *

personnel = dict()

class Application(Frame):
    def __init__(self, master = None):
        self.master = Tk()
        self.master.title('Personnel')
        self.master.geometry('400x300')
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.InputButton = Button(self, text = 'Input information',
                                  command = inputInfo)
        self.OutputButton = Button(self, text = 'Output information',
                                   command = outputInfo)
        self.quitButton = Button(self, text = 'Quit',
                                 command = self.quit)
        self.InputButton.pack()
        self.OutputButton.pack()
        self.quitButton.pack()

def inputInfo():
    strInfo = raw_input('Please input information Number,Name: ')
    lstInfo = strInfo.strip().split(',')
    personnel[lstInfo[0]] = lstInfo[1]

def outputInfo():
    pr = '''(I)D
(N)ame
(Q)uit

Please select the order you use: '''

    while True:
        try:
            choice = raw_input(pr).strip()[0].lower()
        except(EOFError, KeyboardInterrupt):
            choice = 'q'
        print "\nYou picked: [%s]" %choice
        if choice not in 'inq':
            print "Please choose the right choice"
            continue
        break
    if choice == 'q':
        return
    if choice == 'i':
        for i in sorted(personnel):
            print i, '  ', personnel[i]
    else:
        x = personnel.keys()
        y = personnel.values()
        personnel1 = dict(zip(y,x))
        for i in sorted(personnel1):
            print i, ' ', personnel1[i]

if __name__ == "__main__":
    app = Application()
    app.mainloop()

7_9

#!/usr/bin/env python
# encoding: utf-8

def tr(srcstr, dststr, string):
    #we use the low_string to find all kinds of srcstr(capital or not)
    len_string = min(len(srcstr), len(dststr))
    print "The original src is", srcstr
    srcstr = srcstr[:len_string]
    dststr = dststr[:len_string]
    print "after src is: ", srcstr
    low_string = string.lower()
    #we use list 'cause list is hashable
    lst_string = list(string)
    low_srcstr = srcstr.lower()
    #encode_dct stored 2 types of code 
    encode_dct = dict(([srcstr.lower(), dststr.lower()],
                     [srcstr.upper(), dststr.upper()]))
    index = 0
    #len_string is the length of the minimum srcstr and dststr
    #also it's the length of the dict
    while True:
        index = low_string.find(low_srcstr, index)
        if index is -1:
            break
        for i in range(len_string):
            if lst_string[index+i] == srcstr.lower()[i]:
                lst_string[index+i] = dststr.lower()[i]
            else:
                lst_string[index+i] = dststr.upper()[i]
        #update the low_string
        low_string = low_string.replace(srcstr.lower(),
                                        dststr.upper(), 1)
    return ('').join(lst_string)

if __name__ == '__main__':
    ori_string = 'abckedabcdefa'
    print 'the original string is %s' %ori_string
    deststring = tr('abcde', 'mnf', ori_string)
    print 'the destination string is %s' %deststring

7_10

#!/usr/bin/env python
# encoding: utf-8

import string
def rot13(strToEncode):
    availChr = string.lowercase +string.uppercase
    lstToEncode = list(strToEncode)
    for i in range(len(lstToEncode)):
        if strToEncode[i] in string.lowercase:
            iOrd = ord(lstToEncode[i]) - ord('a')
            iOrd = (iOrd+13)%26 + ord('a')
            lstToEncode[i] = chr(iOrd)
        elif strToEncode[i] in string.uppercase:
            iOrd = ord(lstToEncode[i]) - ord('A')
            iOrd = (iOrd+13)%26 + ord('A')
            lstToEncode[i] = chr(iOrd)
    strEncoded = ('').join(lstToEncode)
    print strEncoded
    return strEncoded


rot13('I am Trying to wirte a code')

7_13

在这期间重装了无数回Ubuntu,因为旧的系统用的是windows和Ubuntu一起用,当时是用wubi.exe进行安装的,只能分出30G,我整来整去,把30G的内存弄得快要塞满了。心想,自己也不怎么用windows了,干脆弄了纯Ubuntu的吧,没想到弄了这么久。
安装好之后,运行这个程序,竟然显示没有Tkinter的库,明明说好的是python自带的呀?于是查了一下,重新安装Tkinter之后,成功运行。在此之外,还查到Tkinter在python3中改名为tkinter。穿了马甲python就可能不认识它了,所以import时,最好加上一个异常处理。

#!/usr/bin/env python
# coding: utf-8
try:
    from Tkinter import *
except ImportError:
    #for python3
    from tkinter import *
import random

class Application(Frame):
    def __init__(self, master = None):
        self.master = Tk()
        self.master.title('RandomNumber')
        self.master.geometry('400x300')
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.AddButton = Button(self, text = 'Click to add numbers',
                                  command = AddNumber)
        self.QuitButton = Button(self, text = 'Quit',
                                 command = self.quit)
        self.AddButton.pack()
        self.QuitButton.pack()

A = set()
B = set()
def AddNumber():
    a = random.randrange(0, 10)
    b = random.randrange(0, 10)
    A.add(a)
    B.add(b)
    print 'A is: ', A
    print 'B is: ', B
    print 'A|B is: ', A|B
    print 'A&B is: ', A&B

if __name__ == '__main__':
    app = Application()
    app.mainloop()

7_14

#!/usr/bin/env python
# coding: utf-8
#!/usr/bin/env python
# coding: utf-8
try:
    from Tkinter import *
except ImportError:
    #for python3
    from tkinter import *
import random

class Application(Frame):
    def __init__(self, master = None):
        self.master = Tk()
        self.master.title('RandomNumber')
        self.master.geometry('400x300')
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.AddButton = Button(self, text = 'Click to add numbers',
                                  command = AddNumber)
        self.CertifyButton = Button(self, text = 'Test the result',
                                    command = TestNumber)
        self.QuitButton = Button(self, text = 'Quit',
                                 command = self.quit)
        self.AddButton.pack()
        self.CertifyButton.pack()
        self.QuitButton.pack()

A = set()
B = set()
def AddNumber():
    a = random.randrange(0, 10)
    b = random.randrange(0, 10)
    A.add(a)
    B.add(b)
    print 'A is: ', A
    print 'B is: ', B

def TestNumber():
    for i in range(3):
        AandB = raw_input("Please input A&B: ")
        AorB = raw_input("Please input A|B: ")
        lstAandB = AandB.split()
        lstNumAandB = [int(i) for i in lstAandB]
        setAandB = set(lstNumAandB)
        lstAorB = AorB.split()
        lstNumAorB = [int(i) for i in lstAorB]
        setAorB = set(lstNumAorB)
        if(setAandB == A&B and setAorB == A|B):
            print 'The answer is right!'
        else:
            print 'The answer is wrong! Please reanswer again.'

if __name__ == '__main__':
    app = Application()
    app.mainloop()

7_16

这道题目没找到思路,等学到后面,会了之后,回头来做。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值