您的位置:首页 > 编程语言 > Python开发

《Python核心编程》第7章 习题

2017-03-10 17:59 302 查看
7–3. 字典和列表的方法。

(a) 创建一个字典,并把这个字典中的键按照字母顺序显示出来。

(b) 现在根据已按照字母顺序排序好的键,显示出这个字典中的键和值。

(c)同(b),但这次是根据已按照字母顺序排序好的字典的值,显示出这个字典中的键和值。(注意:对字典和哈希表来说,这样做一般没有什么实际意义,因为大多数访问和排序(如果需要)都是基于字典的键,这里只把它作为一个练习。)

[python] view
plain copy

dicta=dict(b=2,a=1,c=3)

for key in sorted(dicta):

print key

dicta=dict(b=2,a=1,c=3)

for key in sorted(dicta):

print 'key=%s, value=%s' %(key,dicta[key])

dicta={2:'b',1:'a',3:'c'}

listvalue = dicta.values()

listvalue.sort()

for value in listvalue:

for key in dicta.keys():

if value == dicta[key]:

print 'key=%s, value=%s' %(key,dicta[key])

7-4. 建立字典。

给定两个长度相同的列表,比如说,列表[1, 2, 3,...]和['abc', 'def','ghi',...],用这两个列表里的所有数据组成一个字典,像这样:{1:'abc', 2: 'def', 3: 'ghi',...}

[python] view
plain copy

dicta=dict(zip([1,2,3],['abc','def','ghi']))

print dicta

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)合并“新用户”和“老用户”两个选项。如果一个新用户试图用一个不存在的用户名登录,

询问该用户是否是新用户,如果回答是肯定的,就创建该帐户。否则,按照老用户的方式登录。

[python] view
plain copy

from datetime import datetime

import hashlib

db={}

def newuser():

value=[]

prompt='login name desired again: '

while True:

name=raw_input(prompt).lower()

if not name.isalnum() and '' in name:

print 'name format error'

continue

else:

if db.has_key(name):

prompt='name taken,try another: '

continue

else:

break

pwd=raw_input('login passwd desired: ')

m=hashlib.md5()

m.update(pwd)

value.append(m.hexdigest())

value.append(datetime.now())

db[name]=value

print 'new user is %s, register time is %s' %(name,db[name][1])

def olduser():

name=raw_input('login name desired again: ').lower()

pwd=raw_input('login passwd desired: ')

m=hashlib.md5()

m.update(pwd)

passwd=db.get(name)

if passwd[0]==m.hexdigest():

newtime=datetime.now()

if (newtime-db[name][1]).days==0 and (newtime-db[name][1]).seconds<14400:

print 'you already logged in at %s: ' %(db[name][1])

else:

passwd[1]=newtime

print 'welcome back %s, login time is %s' %(name,passwd[1])

else:

print 'login incorrect'

def removeuser():

print db

name=raw_input('input a user name to remove: ').lower()

if name in db:

db.pop(name)

else:

print 'input error'

def userlogin():

while True:

name=raw_input('login name desired: ').lower()

if not name.isalnum() and '' in name:

print 'name format error'

continue

else:

if not db.has_key(name):

print 'user name is not in db'

answer=raw_input('register a new user? y/n').lower()

if 'y'==answer:

newuser()

break

elif 'n'==answer:

break

else:

print 'user name is already in db'

olduser()

break

def showmenu():

prompt="""

(U)ser Login

(R)emove a existing user

(Q)uit

Enter choice:"""

done=False

while not done:

chosen=False

while not chosen:

try:

choice=raw_input(prompt).strip()[0].lower()

except (EOFError,keyboardInterrupt):

choice='q'

print '\nYou picked: [%s]' % choice

if choice not in 'urq':

print 'invalid option,try again'

else:

chosen=True

if choice=='q':

done=True

if choice=='r':

removeuser()

if choice=='u':

userlogin()

if __name__=='__main__':

showmenu()


7-6. 列表和字典。

创建一个简单的股票证券投资数据系统。其中应至少包含四项数据:股市行情显示器符号,所持有的股票,购买价格及当前价位 - 你可以随意添加其他数据项,比如收益率,52 周最高指数、最低指数,等等。用户每次输入各列的数据构成一个输出行。每行数据构成一个列表。还有一个总列表,包括了所有行的数据。数据输入完毕后,提示用户选择一列数据项进行排序。把该数据项抽取出来作为字典的键,字典的值就是该键对应行的值的列表。提醒读者:被选择用来排序的数据项必须是非重复的键,否则就会丢失数据,因为字典不允许一个键有多个值。你还可以选择其他计算输出,比如,盈亏比率,目前证券资产价值等。

[python] view
plain copy

tlist=[]

idict={}

while True:

mark=raw_input('pls input a stock mark: ')

if mark=='--':

break

stock=raw_input('pls input a stock name: ')

price=raw_input('pls input a stock price: ')

current=raw_input('pls input a stock current price: ')

print

tlist.append([mark,stock,price,current])

print '0 mark'

print '1 stock'

while True:

num=int(raw_input('pls input a key to sort: '))

if num==0:

for i in range(0,len(tlist)):

idict.update({}.fromkeys(tlist[i][0],tlist[i]))

for eachkey in sorted(idict):

print 'idict key ',eachkey,' has value ',idict[eachkey]

break

elif num==1:

for i in range(0,len(tlist)):

idict.update({}.fromkeys(tlist[i][1],tlist[i]))

for eachkey in sorted(idict):

print 'idict key ',eachkey,' has value ',idict[eachkey]

break

else:

print 'input key wrong'

continue

7-7. 颠倒字典中的键和值。用一个字典做输入,输出另一个字典,用前者的键做值,前者的值做键。

[python] view
plain copy

idict={1:'a',2:'b',3:'c'}

def changedict(tdict):

mydict={}

for key in tdict:

mydict.update({}.fromkeys(tdict[key],key))

print mydict

changedict(idict)

7-8. 人力资源。

创建一个简单的雇员姓名和编号的程序。让用户输入一组雇员姓名和编号。你的程序可以提供按照姓名排序输出的功能,雇员姓名显示在前面,后面是对应的雇员编号。附加题:添加一项功能,按照雇员编号的顺序输出数据。

[python] view
plain copy

dict1={}

dict2={}

while True:

name=raw_input('pls input a worker name: ')

if name=='--':

break

number=raw_input('pls input a worker number: ')

dict1[name]=number

dict2[number]=name

for key in sorted(dict1):

print key,dict1[key]

print

for key in sorted(dict2):

print key,dict2[key]

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(), 但它们并不一定是解决这个问题所必不可少的函数。

(b) 在这个函数里增加一个标志符参数,来处理不区分大小写的翻译问题。

(c)修改你的程序,使它能够处理删除字符的操作。字符串srcstr 中不能够映射到字符串dststr中字符的多余字符都将被过滤掉。换句话说,这些字符没有映射到dststr 字符串中的任何字符,因此就从函数返回的字符里被过滤掉了。举例来说:如果 srcstr == 'abcdef', dststr == 'mno',string == 'abcdefghi',
那么tr()将输出'mnoghi'. 注意这里len(srcstr) >= len(dststr).

[python] view
plain copy

srcstr1='abc'

dststr1='mno'

string1='Abcdef'

srcstr2='abcDef'

dststr2='mno'

string2='Abcdefghi'

def tr(srcstr,dststr,string,case=0):

mylist=[]

if 0==case:

dicta=dict(zip(srcstr.lower(),dststr))

if len(srcstr)>len(dststr):

dicta.update({}.fromkeys(srcstr[len(dststr):]))

for ch in string.lower():

if ch in dicta:

mylist.append(dicta[ch])

else:

mylist.append(ch)

else:

dicta=dict(zip(srcstr,dststr))

if len(srcstr)>len(dststr):

dicta.update({}.fromkeys(srcstr[len(dststr):]))

for ch in string:

if ch in dicta:

mylist.append(dicta[ch])

else:

mylist.append(ch)

mylist = [ch for ch in mylist if ch]

print ''.join(mylist)

tr(srcstr1,dststr1,string1,0)

tr(srcstr2,dststr2,string2,1)

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: [Thisis
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: [Guvfvf
n fubeg fragrapr.].

The rot13 string is: [This is a short sentence.].

[python] view
plain copy

import string

upperdict={}

lowerdict={}

upperletters=string.uppercase

lowerletters=string.lowercase

dststr=[]

oristr=raw_input('Enter string to rot13: ')

print 'Your string to en/crypt was: ',oristr

for i in range(0,len(lowerletters)):

if i<13:

lowerdict[lowerletters[i]]=lowerletters[i+13]

else:

lowerdict[lowerletters[i]]=lowerletters[i-13]

for i in range(0,len(upperletters)):

if i<13:

upperdict[upperletters[i]]=upperletters[i+13]

else:

upperdict[upperletters[i]]=upperletters[i-13]

for ch in oristr:

if ch in lowerdict:

dststr.append(lowerdict[ch])

elif ch in upperdict:

dststr.append(upperdict[ch])

else:

dststr.append(ch)

dststr=''.join(dststr)

print 'the rot13 string is: ',dststr

7–13. 随机数。

修改练习5-17 的代码:使用random 模块中的randint()或randrange()方法生成一个随机数集合:从0 到9(包括9)中随机选择,生成1 到10 个随机数。这些数字组成集合A(A 可以是可变集合,也可以不是)。同理,按此方法生成集合B。每次新生成集合A 和B 后,显示结果 A | B 和 A & B

[python] view
plain copy

import random

tmp=[]

for i in range(0,10):

tmp.append(random.randint(0,9))

A=set(tmp)

tmp=[]

for i in range(0,10):

tmp.append(random.randrange(0,10))

B=set(tmp)

print A

print B

print A|B

print A&B

7-14. 用户验证。修改前面的练习,要求用户输入A|B和A&B的结果,并告诉用户的答案是否正确,而不是将A|B和A&B的结果直接显示出来。如果用户回答错误,允许他修改解决方案,然后重新验证用户输入的答案。如果用户三次提交的答案均不正确,程序将显示正确结果。附加题:运用你关于集合的知识,创建某个集合的潜在子集,并询问用户此潜在子集是否真是该集合的子集,要求和主程序一样有显示更正和答案的功能。

[python] view
plain copy

import random

tmp=[]

for i in range(0,10):

tmp.append(random.randint(0,9))

A=set(tmp)

tmp=[]

for i in range(0,10):

tmp.append(random.randrange(0,10))

B=set(tmp)

print A

print B

tmpanwser1=[]

anwser1=[]

for i in range(0,3):

tmpanwser1=raw_input('pls input anwser for A|B,seprate by comma: ').split(',')

for j in tmpanwser1:

anwser1.append(int(j))

C=set(anwser1)

if C==(A|B):

print 'you are right'

break

elif 2==i:

print 'the anwser of A|B is: ',A|B

else:

print 'you are wrong'

tmpanwser2=[]

anwser2=[]

for i in range(0,3):

tmpanwser2=raw_input('pls input anwser for A&B,seprate by comma: ').split(',')

for j in tmpanwser2:

anwser2.append(int(j))

C=set(anwser2)

if C==(A&B):

print 'you are right'

break

elif 2==i:

print 'the anwser of A&B is: ',A&B

else:

print 'you are wrong'

#additional question

tmp=[]

for i in range(0,10):

tmp.append(random.randint(0,9))

D=set(tmp)

tmp=[]

for i in range(0,6):

tmp.append(random.randrange(1,9))

E=set(tmp)

print 'set D is ',D

print 'set E is ',E

for i in range(0,2):

tmpanwser3=raw_input('set E is subset of set D,y/n? ')

if 'y'==tmpanwser3:

if E.issubset(D):

print 'you are right'

break

elif 1==i:

print 'the subset of D is ',D.intersection(E)

else:

print 'you are wrong'

elif 'n'==tmpanwser3:

if E.issubset(D):

print 'you are wrong'

elif 1==i:

print 'the subset of D is ',D.intersection(E)

else:

print 'you are right'

break

else:

print 'input error,only y/n valid'

7–15. 编写计算器。

这个练习取材于http://math.hws.edu/ 在线免费Java 教材中的练习12.2。编写一个程序允许用户选择两个集合:A 和B,
及运算操作符。例如,in, not in, &, |, ^, <,<=, >, >=, ==, !=, 等. (你自己定义集合的输入语法,它们并不一定要像Java 示例中那样用方括号括住。)解析输入的字符串,按照用户选择的运算进行操作。你写的程序代码应该比Java 版本的该程序更简洁。

[python] view
plain copy

tmp1=eval(raw_input('pls input set A,separate by comma:'))

tmp2=eval(raw_input('pls input set B:separate by comma:'))

A=set(tmp1)

B=set(tmp2)

print A

print B

while True:

op=raw_input('pls choose a operator from (in,not in,&,|,^,<,<=,>,>=,==,!=) for A operator B:')

if 'in'==op:

print 'A in B is: ',A in B

elif 'not in'==op:

print 'A not in B is: ',A not in B

elif '&'==op:

print 'A & B is: ',A&B

elif '|'==op:

print 'A | B is: ',A|B

elif '^'==op:

print 'A ^ B is: ',A^B

elif '<'==op:

print 'A < B is: ',A<B

elif '<='==op:

print 'A <= B is: ',A<=B

elif '>'==op:

print 'A > B is: ',A>B

elif '>='==op:

print 'A >= B is: ',A>=B

elif '=='==op:

print 'A == B is: ',A==B

elif '!='==op:

print 'A != B is: ',A!=B

else:

print 'input error'

break
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python基础知识