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

6-2. 字符串标识符.修改例 6-1 的 idcheck.py 脚本,使之可以检测长度为一的标识符,并且可以识别 Python 关键字,对后一个要求,你可以使用 keyword 模块(特别是 keyword.kelist)来帮你.

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import string  
  2. import keyword  
  3.   
  4. alphas=string.letters+'_'  
  5. num=string.digits  
  6. aplpnums=alphas+num  
  7.   
  8. print 'Testees must be at least 1 char long.'  
  9. myinput=raw_input('Identifier to test? ')  
  10.   
  11. if len(myinput)>=1:  
  12.     if myinput[0not in alphas:  
  13.         print 'invalid: first symbol must be alphabetic'  
  14.     else:  
  15.         for otherchar in myinput [1:]:  
  16.             if otherchar not in aplpnums:  
  17.                 print 'invalid: remaining symbols must be alphanumeric'  
  18.                 break  
  19.         else:  
  20.             if myinput in keyword.kwlist:  
  21.                 print 'invalid: symbol is reserved as keyword'  
  22.             else:  
  23.                 print 'okay as an identifier'  

6-3 

排序

(a) 输入一串数字,从大到小排列之.

(b) 跟 a 一样,不过要用字典序从大到小排列之

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. (a)  
  2. numstr=raw_input('input some numbers: ')  
  3. numlist=list(numstr)  
  4. n=len(numlist)  
  5. for i in range(0,n):  
  6.     for j in range(0,n-i-1):  
  7.         if int(numlist[j])<int(numlist[j+1]):  
  8.             temp=numlist[j]  
  9.             numlist[j]=numlist[j+1]  
  10.             numlist[j+1]=temp  
  11. numlist.sort()  
  12. numlist.reverse()  
  13. print numlist  
  14. (b)  
  15. numstr=raw_input('input some numbers: ')  
  16. numlist=list(numstr)  
  17. numlist.sort()  
  18. numlist.reverse()  
  19. print numlist  

6-4 算术. 更新上一章里面你的得分测试练习方案,把测试得分放到一个列表中去.你的代码应该可以计算出一个平均分,见练习 2-9 和练习 5-3.

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. score=[65,76,87,98]  
  2. print (sum(score)/len(score))  

6-5 字符串
(a)更新你在练习 2-7 里面的方案,使之可以每次向前向后都显示一个字符串的一个字符.
(b)通过扫描来判断两个字符串是否匹配(不能使用比较操作符或者 cmp()内建函数)。附加题:在你的方案里加入大小写区分.
(c)判断一个字符串是否重现(后面跟前面的一致).附加题:在处理除了严格的回文之外,加入对例如控制符号和空格的支持。
(d)接受一个字符,在其后面加一个反向的拷贝,构成一个回文字符串.

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. (a)  
  2. s=raw_input('Enter a string:')    
  3. i=0    
  4. while i<len(s):    
  5.     print s[0:i+1],  
  6.     i+=1  
  7. print  
  8. j=0  
  9. rs=''  
  10. while j<len(s):  
  11.     rs+=s[-1-j]  
  12.     print rs,  
  13.     j+=1  
  14. (b)  
  15. str1=raw_input('Enter 1st string:')  
  16. str2=raw_input('Enter 2nd string:')  
  17. newstr1=str1.lower()  
  18. newstr2=str2.lower()  
  19. if len(str1) is not len(str2):  
  20.     print "not equal"  
  21. else:  
  22.     for i in range(len(str1)):  
  23.         if newstr1[i] is not newstr2[i]:  
  24.             print "not equal"  
  25.             break  
  26.     else:  
  27.         print "equal"  
  28. (C)  
  29. str=raw_input('Enter 1st string:')  
  30. l=len(str)  
  31. if l % 2 == 0:  
  32.     for i in range(l/2):  
  33.         if str[i]!=str[l-1-i]:  
  34.             print "not repeat"  
  35.             break  
  36.     else:  
  37.         print "repeat"  
  38. elif l % 2 != 0:  
  39.     for i in range(l/2):  
  40.         if str[i]!=str[l-i-1]:  
  41.             print "not repeat"  
  42.             break  
  43.     else:  
  44.         print "repeat"  
  45. (d)  
  46. str1=raw_input('Enter 1st string:')  
  47. str2=str1 + str1[::-1]  
  48. print str2  
 6-6 字符串.创建一个 string.strip()的替代函数:接受一个字符串,去掉它前面和后面的空格(如果使用 string.*strip()函数那本练习就没有意义了) 
 

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. str=raw_input('Enter a string:')  
  2. i=0  
  3. j=len(str)-1  
  4. while 1:  
  5.     if str[i]==' ':  
  6.         i+=1  
  7.     else:  
  8.         break  
  9. while 1:  
  10.     if str[j]==' ':  
  11.         j-=1  
  12.     else:  
  13.         break  
  14. print str[i:j+1]  

6-7 调试.看一下在例 6.5 中给出的代码(buggy.py)
(a)研究这段代码并描述这段代码想做什么.在所有的(#)处都要填写你的注释.
(b)这个程序有一个很大的问题,比如输入 6,12,20,30,等它会死掉,实际上它不能处理任何的偶数,找出原因.
(c)修正(b)中提出的问题.

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #功能:删除列表中能被输入的数整除的元素  
  2. num_str=raw_input('Enter a number: ')  
  3. num_num=int(num_str)  
  4. fac_list=range(1,num_num+1)  
  5. print "before:",fac_list  
  6. i=0  
  7. while i<len(fac_list):  
  8.     if num_num%fac_list[i]==0:  
  9.         del fac_list[i]  
  10.     else:  
  11.         i=i+1  
  12. print "after:",fac_list  

6-8 列表。给出一个整型值,返回代表该值得英文,比如输入89会返回“eight-nine”。附加题:能够返回符合英文语法规律的新式,比如输入89会返回“eighty-nine”。本练习中的值假定在0~1000。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. single=['','one','two','three','four','five','six','seven','eight','nine']  
  2. double1=['ten','eleven','tweleve','thirting','fourting','fifting','sixting','seventing','eighting','nineting']  
  3. double2=['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']  
  4. numstr=raw_input('Enter a number 0--1000: ')  
  5. numlen=len(numstr)  
  6. num=int(numstr)  
  7. if numlen==1:  
  8.     if int(numstr[0])>0:  
  9.         print single[num]  
  10.     else:  
  11.         print 'zero'  
  12. elif numlen==2:  
  13.     if numstr[0]=='1':  
  14.         print double1[num-10]  
  15.     else:  
  16.         print double2[int(numstr[0])]+'-'+single[int(numstr[1])]  
  17. elif numlen==3:  
  18.     if numstr[1]=='1':  
  19.         tmp=double1[int(numstr[2])]  
  20.     else:  
  21.         tmp=double2[int(numstr[1])]+'-'+single[int(numstr[2])]  
  22.     print single[int(numstr[0])]+' hundred '+tmp  
  23. else:  
  24.     print 'one thousand'  

6-9 转换。为练习5-13写一个姊妹函数,接受分钟数,返回小时数和分钟数。总时间不变,并且要求小时尽可能大。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. min=int(raw_input('please input a number as minutes: '))  
  2. def totaltime(min):  
  3.     if min<60:  
  4.         print '0 hours %d minutes' %(min)  
  5.     elif min>=60:  
  6.         print '%d hours %d minutes' %(min/60,min%60)  
  7. totaltime(min)  

6-10 字符串。写一个函数,返回一个跟输入字符串相似的字符串,要求字符串的大小写反转,比如,输入“Mr.Ed”,应该返回“mR.eD”作为输出。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. ostr=raw_input('please input a string: ')  
  2. def changecase(str):  
  3.     dstr=str.swapcase()  
  4.     print dstr  
  5. changecase(ostr)  

6-11 转换。
(a)创建一个从整型到IP地址的转换,如下格式: www.xxx.yyy.zzz
(b)更新你的程序,使之可以逆转换。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. a)ip=int(raw_input('please input a number as IP: '))  
  2. print 'IP'+'='+str(int(int(ip)/16777216) & 255)+'.'\  
  3.       +str(int(int(ip)/65536) & 255)+'.'+str(int(int(ip)/256) & 255)+'.'+str((int(ip) & 255))  
  4. b)ip=raw_input('please input a IP like xxx.xxx.xxx.xxx : ')  
  5. print 'IP'+'='+str(int(ip.split('.')[0])*16777216+int(ip.split('.')[1])*65536+\  
  6.                    int(ip.split('.')[2])*256+int(ip.split('.')[3]))  

6-12 字符串。
(a)创建一个名字为findchr()的函数,函数声明如下。
def findchr(string, char)
findchr()要在字符串string中查找字符char,找到就返回该值得索引,否则返回-1。不能用string.*find()或者string.*index()函数和方法。
(b)创建另一个叫rfindchr()的函数,查找字符char最后一次出现的位置。它跟findchr()工作类似,不过它是从字符串的最后开始向前查找的。
(c)创建第三个函数,名字叫subchr(),声明如下。
def subchr(string, origchar, newchar)
subchr()跟findchr()类似,不同的是,如果找到匹配的字符就用新的字符替换原先字符。返回修改后的字符串。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. a)  
  2. def findchr(string, char):  
  3.     strlen=len(string)  
  4.     if char in string:  
  5.         for i in range(strlen):  
  6.             if char==string[i]:  
  7.                 print i  
  8.     else:  
  9.         print -1  
  10. b)  
  11. def rfindchr(string, char):  
  12.     strlen=len(string)  
  13.     if char in string:  
  14.         for i in range(strlen):  
  15.             if char==string[-1-i]:  
  16.                 print strlen-i-1  
  17.                 break  
  18.     else:  
  19.         print -1  
  20. c)  
  21. def subchr(string, origchar, newchar):  
  22.     while(1):  
  23.         if findchr(string,origchar)==-1:  
  24.             break  
  25.         else:  
  26.             p=findchr(string,origchar)  
  27.             string=string[:p]+newchar+string[p+1:]  
  28.     print string  

6-13 字符串.string模块包含三个函数,atoi(),atol()和atof(),他们分别负责把字符串转换成整型、长整型和浮点型数字。从Python 1.5起,Python的内建函数int()、long()、float()也可以做同样的事了,本文来,complex()函数可以把字符串转换成复数(然而1.5之前,这些转换函数只能工作于数字之上)
string模块中并没有实现一个atoc()函数,那么你来实现一个atoc(),接受单个字符串做参数输入,一个表示复数的字符串,例如'-1.23e+4-5.67j',返回相应的复数对象。你不能用eval()函数,但可以使用complex()函数,而且你只能在如下的限制之下使用:complex():complex(real, imag)的real和imag都必须是浮点值。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. str=raw_input('input a string as comlex number:')  
  2. def atoc(str):  
  3.     strlen=len(str)  
  4.     for i in range(strlen):  
  5.         if '+'==str[-1-i] or '-'==str[-1-i]:  
  6.             op1=str[:-1-i]  
  7.             op2=str[-1-i:-1]  
  8.             break  
  9.         else:  
  10.             continue  
  11.     print complex(float(op1),float(op2))          
  12. atoc(str)  

6-14 随机数。设计一个“石头、剪子、布”游戏,有时又叫“Rochambeau”,你小时候可能玩过,下面是规则。你和你的对手,在同一时间做出特定的手势,必须是下面一种:石头、剪子、布。胜利者从下面的规则产生,这个规则本身是个悖论。(a)布包石头。(b)石头砸剪子。(c)剪子剪破布。在你的计算机版本中,用户输入他/她的选项,计算机找一个随机选项,然后由你的程序来决定一个胜利者或者平手。注意,最好的算法是尽量少使用if语句。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import random  
  2.   
  3. print '0 siccsor'  
  4. print '1 stone'  
  5. print '2 fabric'  
  6. print '3 quit'  
  7.   
  8. list = ['siccsor','stone','fabric']  
  9. while True:  
  10.     i = input("pls input operation number: ")  
  11.     if (3 == i):  
  12.         break  
  13.     elif (i<0 or i>3):  
  14.         print 'Error input operation, try agin. 3 operation is quit\n'  
  15.         continue  
  16.     c = random.randint(0,2)  
  17.     if (i == c):  
  18.         print 'your is %s, computer is %s ' % (list[i],list[c])  
  19.         print 'it is draw'  
  20.     elif (i-c) == 2 or (i-c) == -1:  
  21.         print 'your is %s, computer is %s ' % (list[i],list[c])  
  22.         print 'computer win'  
  23.     else:  
  24.         print 'your is %s, computer is %s ' % (list[i],list[c])  
  25.         print 'you win'  

6-15 转换。
(a)给出两个可识别格式的日期,比如MM/DD/YY或者DD/MM/YY格式。计算出两个日期之间的天数。
(b)给出一个人的生日,计算此人从出生到现在的天数,包括所有的闰月。
(c)还是上面的例子,计算出此人下次过生日还有多少天。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import time  
  2.   
  3. def isLeapYear(year):  
  4.     if (year%4==0 and year%100!=0or (year%400==0):  
  5.         return True  
  6.   
  7. def IntervalDays(str1,str2):  
  8.     month1 = [0,31,28,31,30,31,30,31,31,30,31,30,31]  
  9.     month2 = [0,31,29,31,30,31,30,31,31,30,31,30,31]  
  10. #假定输入的日期都是正确的且后一个日期比前一个日期大  
  11.     bdate = str1.split('/')  
  12.     bdate[0],bdate[1],bdate[2]=int(bdate[0]),int(bdate[1]),int(bdate[2])  
  13.     edate = str2.split('/')  
  14.     edate[0],edate[1],edate[2]=int(edate[0]),int(edate[1]),int(edate[2])  
  15.     if bdate==edate:  
  16.         print '0 days'  
  17.     elif bdate[1]==edate[1and bdate[2]==edate[2]:  
  18.         print '%d days' %abs(bdate[0]-edate[0])  
  19.     elif bdate[1]!=edate[1and bdate[2]==edate[2]:  
  20.         bdays=0  
  21.         edays=0  
  22.         if isLeapYear(bdate[2]):  
  23.             for i in range(1,bdate[1]):  
  24.                 bdays+=month2[i]  
  25.             bdays=bdays+bdate[0]  
  26.             for i in range(1,edate[1]):  
  27.                 edays+=month2[i]  
  28.             edays=edays+edate[0]  
  29.             print '%d days' %abs(edays-bdays)  
  30.         else:  
  31.             for i in range(1,bdate[1]):  
  32.                 bdays+=month1[i]  
  33.             bdays=bdays+bdate[0]  
  34.             for i in range(1,edate[1]):  
  35.                 edays+=month1[i]  
  36.             edays=edays+edate[0]  
  37.             print '%d days' %abs(edays-bdays)  
  38.     elif bdate[2]!=edate[2]:  
  39.         days=0  
  40.         for i in range(bdate[2]+1,edate[2]):  
  41.             if isLeapYear(i):  
  42.                 days+=366  
  43.             else:  
  44.                 days+=365  
  45.         if isLeapYear(bdate[2]):  
  46.             for i in range(bdate[1]+1,13):  
  47.                 days+=month2[i]  
  48.             days+=(month2[bdate[1]]-bdate[0])  
  49.         else:  
  50.             for i in range(bdate[1]+1,13):  
  51.                 days+=month1[i]  
  52.             days+=(month1[bdate[1]]-bdate[0])  
  53.         if isLeapYear(edate[2]):  
  54.             for i in range(1,edate[1]):  
  55.                 days+=month2[i]  
  56.             days+=edate[0]  
  57.             print '%d days' %(days)  
  58.         else:  
  59.             for i in range(1,edate[1]):  
  60.                 days+=month1[i]  
  61.             days+=edate[0]  
  62.             print '%d days' %(days)  
  63.   
  64. if __name__=='__main__':  
  65.     #(a)  
  66.     date1=raw_input("input a start date as DD/MM/YYYY: ")  
  67.     date2=raw_input("input a end date as DD/MM/YYYY: ")  
  68.     IntervalDays(date1,date2)  
  69.     #(b)  
  70.     birth=raw_input("input a birth date as DD/MM/YYYY: ")  
  71.     today=str(time.strftime("%d/%m/%Y"))  
  72.     print 'today is %s ' %today  
  73.     IntervalDays(birth,today)  
  74.     #(c)  
  75.     birth=raw_input("input a birth date as DD/MM/YYYY: ")  
  76.     today=str(time.strftime("%d/%m/%Y"))  
  77.     print 'today is %s ' %today  
  78.     if today.split('/')[1]<birth.split('/')[1]:  
  79.         nbirth=str(birth.split('/')[0]+'/'+birth.split('/')[1]+'/'+today.split('/')[2])  
  80.         IntervalDays(today,nbirth)  
  81.     elif today.split('/')[1]==birth.split('/')[1]:  
  82.         if today.split('/')[0]<birth.split('/')[0]:  
  83.             print '%d days' %(int(birth.split('/')[0])-int(today.split('/')[0]))  
  84.         else:  
  85.             year=int(today.split('/')[2])+1  
  86.             nbirth=str(birth.split('/')[0]+'/'+birth.split('/')[1]+'/'+str(year))  
  87.             IntervalDays(today,nbirth)  

6-16 矩阵。处理矩阵M和N的加和乘操作。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. a)两个矩阵的维数相等才能相加  
  2. a = ([1,2,3],[4,5,6],[7,8,9])  
  3. b = ([9,8,7],[6,5,4],[3,2,1])  
  4.   
  5. c = ([0,0,0],[0,0,0],[0,0,0])  
  6. for i in range(0,len(a)):  
  7.     for j in range(0,len(b)):  
  8.         c[i][j] = a[i][j]+b[i][j]  
  9. print c   
  10.   
  11. b)矩阵1的列数与矩阵2的行数相等两个矩阵才能相乘  
  12. a = ([1,2,3,4],[5,6,5,8],[9,10,11,12])  
  13. b = ([1,1,1],[1,1,1],[1,1,1],[1,1,1])  
  14.   
  15. c = ([0,0,0],[0,0,0],[0,0,0])  
  16. for m in range(0,len(c)):  
  17.     for i in range(0,len(a)):  
  18.         for j in range(0,len(b)):  
  19.             c[m][i] += a[i][j]*b[j][i]  
  20. print c  

6-17 方法。实现一个叫myPop()的函数,功能类似于列表的pop()方法,用一个列表作为输入,移除列表的最新一个元素,并返回它。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. l=[1,2,3,4,5]  
  2. def mypop(list):  
  3.     tmp=list[-1]  
  4.     del list[-1]  
  5.     return tmp  
  6. print mypop(l)  
  7. print l  


6-18 zip()内建函数。在6.13.2节里面关于zip()函数的例子中,zip(fn,ln)返回的是什么?

返回一个列表,列表中的每个元素是一个元组

6-19 多列输出。有任意项的序列或者其他容器,把它们等距离分列显示。由调用者提供数据和输出格式。例如,如果你传入100个项并定义3列输出,按照需要的模式显示这些数据。这种情况下,应该是两列显示33个项,最后一列显示34个。你可以让用户来选者水平排序或者垂直排序。

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import random  
  2.   
  3. list = []  
  4. nums = input("pls input a number for iterms: ")  
  5. clns = input("pls input a number for columns: ")  
  6. for i in range(0,nums):  
  7.     list.append(i+1)  
  8. print list  
  9. print '0 horizontal sort'  
  10. print '1 vertical sort'  
  11. print '2 quit'  
  12. while True:  
  13.     print  
  14.     i = input("pls input operation number: ")  
  15.     if (2 == i):  
  16.         break  
  17.     elif (i<0 or i>2):  
  18.         print 'Error input operation, try agin. 3 operation is quit\n'  
  19.         continue  
  20.     if (0 == i):  
  21.         n = 0  
  22.         for m in range(0,nums):  
  23.             print "%4d" %list[m],  
  24.             n += 1  
  25.             if n % clns == 0:  
  26.                 print  
  27.     elif (1 == i):  
  28.         n = 0  
  29.         for i in range(0,nums/clns+1):  
  30.             if i == nums/clns:  
  31.                 for j in range(0,nums%clns):  
  32.                     print 4*clns*' '+str(list[i*clns+j])  
  33.             else:  
  34.                 for j in range(0,clns):  
  35.                     print "%4s" %str(list[i+j*(nums/clns)]),  
  36.                 print  
  37.             n += 1  
  38.             if n % clns == 0:  
  39.                 continue  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值