python核心编程笔记——Chapter6

时间:2021-07-18 22:45:52

Chapter 6.序列:字符串,列表和元组

这章内容比较多啊,看得比较久,而且题目又难很多。

6.1鉴定一个字符串是否是另外一个字符串的字串,这道题目不是很确定,好像没有直接的判定吧。

直接是否内建的序列函数 in ?

1 >>> a = 'or'
2 >>> b = 'favorite'
3 >>> a in b
4 True

strin模块也有类似的函数,不知道算不算

 1 >>> b.count(a)
 2 1
 3 >>> b.find(a)
 4 3
 5 >>> b.index(a)
 6 3
 7 >>> b.rindex(a)
 8 3
 9 >>> b.rindex(a)
10 3

6-2。修改idcheck.py脚本,使之可以检测长度为一的标识符,并且可以识别Python关键字(通过keyword模块的keyword.kwlist)来辅助。

其实不太难,跟着感觉走就对了。

python核心编程笔记——Chapter6python核心编程笔记——Chapter6
 1 #!/usr/bin/env python
 2 #-*-coding=utf-8-*-
 3 
 4 import string 
 5 import keyword
 6 
 7 alphas = string.letters + '_'
 8 nums = string.digits
 9 keywords = keyword.kwlist
10 
11 flag = True
12 
13 print 'Welcome to the Identifier Checker v2.0'
14 myInput = raw_input('Identifier to test?')
15 
16 if len(myInput) >= 0:
17     if myInput in keywords:
18         flag = False
19         print '''invalid:the identifier must not be keyword.'''
20     elif myInput[0] not in alphas:
21         flag = False
22         print '''invalid:first symbol must be alphabetic'''
23     else:
24         for otherChar in myInput[1:]:
25             if otherChar not in alphas+nums:
26                 flag = False
27                 print '''invalid:remaining symbols must be alphanumeric'''
28                 break
29     
30     if flag == True:
31         print '''okay as an identifier'''
32 
33     
View Code

6-3.对输入的一串数字分别进行从大到小的排列和用字典序从大到小排序,没难度,注意按字典序排序用的是sorted()函数

 1 #!/usr/bin/env python
 2 #-*-coding=utf-8-*-
 3 
 4 s = []
 5 a = input('请输入数字,输入0退出:')
 6 s.append(a)
 7 
 8 while a != 0 :
 9     a = input('请输入数字,输入0退出:')
10     s.append(a)
11 s.sort(reverse = True)
12 print '从大到小排序得:',s
13 print '按照字典序从大到小排列得:',sorted(s,reverse = True)

6-6.创建一个string.strip()的替代函数。难度不大,由于字符串内部是不可变的,改变字符串估计得用切片操作了。

 1 #!/usr/bin/env python
 2 #-*-coding=utf-8-*-
 3 
 4 def Strips(str):
 5     for i in range(len(str)):
 6         if str[i] != ' ':
 7             str = str[i:]
 8             break
 9     for i in  range(-1,-len(str)-1,-1):
10         if str[i] != ' ':
11             str = str[:i+1]
12             break
13     return str
14 
15 if __name__ == '__main__':
16     str = raw_input('请输入字符串:')
17     print Strips(str)

6-7.修改那个有bug的程序buggy.py,可以看看,目测那个程序应该是用来剔除序列长度的因子吧,修改一下bug得到:

 1 #!/usr/bin/env python 
 2 #-*-coding=utf-8-*-
 3 
 4 #
 5 num_str = raw_input('Enter a number: ')
 6 
 7 #
 8 num_num = int(num_str)
 9 
10 #
11 fac_list = range(1,num_num+1)
12 print "BEFORE:",fac_list
13 
14 #
15 i = 0
16 
17 #
18 while i < len(fac_list):
19     #
20     if num_num % fac_list[i] == 0:
21         del fac_list[i]
22         i -= 1
23     
24     #
25     i += 1
26 
27 #
28 print "AFTER:",fac_list

6-8.这道题目有点难度,要将一个数字转成合乎语法的英语单词,思路还是找两个列表把单词存起来。

 1 #!/usr/bin/env python
 2 #-*-coding=utf-8-*-
 3 
 4 def change(num):
 5     num_a = int(num)
 6     list1 = ['zero','one','two','three','four','five','six','seven','eight','nine',\
 7         'ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen',\
 8         'eighteen','nineteen']
 9     list2 = ['zero','ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
10     if num_a == 1000:
11         return 'one thousand'
12     if num_a == 0:
13         return 'zero'
14     if num_a >= 100 and num_a % 100 == 0:
15         return list1[num_a / 100] + ' hundred'
16     str = ''
17     if num_a / 100 > 0 :
18         str += list1[num_a / 100] + ' hundred and '
19         num_a %= 100
20     if num_a % 10 == 0:
21         str += list2[num_a / 10]
22         return str
23     elif num_a < 20:
24         str += list1[num_a]
25         return str
26     else:
27         str += list2[num_a / 10] + '-' + list1[num_a % 10]
28         return str
29 
30 if __name__ == '__main__':
31     num = raw_input('请输入数字:')
32     print change(num)

6-10.转换,返回一个大小写反转的字符串,不难,用个突然发现string有个swapcase()的内建函数,能够翻转string的大小写,写都不用写了

1 >>> cc = 'Mr.Ed'
2 >>> cc.swapcase()
3 'mR.eD'

6-11.转换。写一个能从整型到IP地址相互转化的程序。这道题目一开始不懂得是什么意思,后来看网上大牛的回答,才知道考查的是10进制数与256进制数之间的相互转化。这里直接贴上大牛的代码,不班门弄斧了。值得一体的是,python3.3之后新增了ipaddress模块,可以直接使用。

 1 #!/usr/bin/env python
 2 #-*-coding=utf-8-*-
 3 
 4 def IntegerToIP(num):
 5     "Integer to IP"
 6     IP = [] 
 7     for i in range(4):
 8         IP.append(str(num%256))
 9         num /= 256
10     return '.'.join(IP[::-1])
11 
12 def IPToInteger(IP):
13     "IP to Interger"
14     Integer = 0
15     node = []
16     node = IP.split('.')
17 
18     for i in range(-1,-len(node)-1,-1) :
19         x = -(i+1) 
20         Integer += int(node[i]) * (256 ** x)
21 
22     return Integer
23 
24 def test() :
25     "Just for test"
26     num = input("Enter a int Num : ") 
27     print "The Integer to IP Address is : " ,IntegerToIP(num)
28     print "The IP Address to Integer is : " ,IPToInteger(IntegerToIP(num))
29 
30 if '__main__' ==  __name__ :
31     test()  

6-12.字符串,自己实现在字符串里面索引的函数

 1 #!/usr/bin/env python
 2 #-*-coding=utf-8-*-
 3 
 4 def findchr(string,char):
 5     for i in range(len(string)):
 6         if string[i] == char:
 7             return i
 8 
 9     return -1
10 
11 def rfindchr(string,char):
12     for i in range(-1,-len(string)-1,-1):
13         if string[i] == char:
14             return i+len(string)
15     return -1
16 
17 def subchr(string,origchar,newchar):
18     str = ''
19     for ochar in string:
20         if ochar == origchar:
21             ochar = newchar
22         str += ochar
23     return str
24 
25 def test():
26     s1 =  'finish'
27     s2 = 'i'
28     s3 = 'a'
29     print findchr(s1,s2)
30     print rfindchr(s1,s2)
31     print subchr(s1,s2,s3)
32 
33 if __name__ =='__main__':
34     test()             

6-13.实现一个atoc(),其实python2.7已经完善了complex()函数,书上的例子直接可以用complex()来实现,跳过。

1 >>> b = complex('-1.23e+4-5.67j')
2 >>> type(b)
3 <type 'complex'>
4 >>> print b
5 (-12300-5.67j)

6-14.模拟剪刀石头布游戏,java写过,不想写了。

6-15.求出两个日子的时间差,选用datetime模块超方便

 1 #!/usr/bin/env python
 2 #-*-coding=utf-8-*-
 3 
 4 import datetime
 5 
 6 def datedelta(date1,date2):
 7     l1 = date1.split('/')
 8     l2 = date2.split('/')
 9     datetime1 = datetime.date(int(l1[0]),int(l1[1]),int(l1[2]))
10     datetime2 = datetime.date(int(l2[0]),int(l2[1]),int(l2[2]))
11     return (datetime2 - datetime1).days
12 
13 def birthday(date):
14     l1 = date.split('/')
15     Date = datetime.date(int(l1[0]),int(l1[1]),int(l1[2]))
16     Today = datetime.date.today()
17     return (Today-Date).days
18 
19 def nextbirthday(date):
20     l1 = date.split('/')
21     Today = datetime.date.today()
22     Year = Today.year
23     Date1 = datetime.date(Year,int(l1[1]),int(l1[2]))
24     Date2 = datetime.date(Year+1,int(l1[1]),int(l1[2]))
25     if (Date1 - Today).days > 0:
26                return (Date1 - Today).days
27     else:
28         return (Date2 - Today).days
29 
30 if __name__ == '__main__':
31     print '请输入两个可识别的日期:'
32     d1 = raw_input('date1:')
33     d2 = raw_input('date2:')
34     d1 = d1.strip()
35     d2 = d2.strip()
36     print '两个日期之间的天数为:',datedelta(d1,d2),'days'
37     birth = raw_input('请输入你的生日:')
38     print '从你出生到现在的天数为:',birthday(birth),'days'
39     print '到你下次过生日还有:',nextbirthday(birth),'days'

6-16.矩阵,处理矩阵M与N的加和乘运算,直接使用那个numpy模块,直接搞定。

 1 >>> from numpy import matrix
 2 >>> M = matrix('1,2,3;2,3,4;3,4,5')
 3 >>> N = matrix('1,2,3;2,3,4;3,4,5')
 4 >>> M+N
 5 matrix([[ 2,  4,  6],
 6         [ 4,  6,  8],
 7         [ 6,  8, 10]])
 8 >>> M*N
 9 matrix([[14, 20, 26],
10         [20, 29, 38],
11         [26, 38, 50]])

6-17.实现一个myPop()函数,用一个列表作为输入,移除列表的最新一个元素,并返回它。看不懂题目,首先何谓最新,如果列表之前中间新插入一个数,但方法无法跟踪啊。

所以不做了。

6-18.看网上的答案都说返回元组,但是我自己写了个却是返回list类型到底谁对谁错呢?

1 >>> fn=['hello','hi','ha']
2 >>> ls=['John','Tony','Kelly']
3 >>> zip(fn,ls)
4 [('hello', 'John'), ('hi', 'Tony'), ('ha', 'Kelly')]
5 >>> type(zip(fn,ls))
6 <type 'list'>

6-19.太麻烦了,不想写,而且似乎要考虑的东西和细节蛮多的,建议大家看看这个大牛的csdn博客,程序一遍遍地修改,非常屌!

http://blog.csdn.net/fzyz_sb/article/details/8986260

 

就这样,请多多指教!