首页 > 编程语言 > 详细

python核心编程(第二版)-------第六章课后习题

时间:2015-11-26 06:51:51      阅读:275      评论:0      收藏:0      [点我收藏+]

6-1.字符串。string模块中是否有一种字符串方法或者函数可以帮助我鉴定一下字符串是否是另一个大字符穿的一部分?

答案: 存在一个方法:find(sub, beg, end)

        参数解释:(1)sub是要检测的子字符串;

                      (2)beg是大字符穿中检索时的起始位置,默认值是0;

                      (3)end是检索时的终止位置,默认是-1

                      (4)[beg, end]类似于索引切片,最终检索位置不包括end

        返回值:(1)如果检索成功,返回sub串出现的位置

                  (2)如果失败,返回-1

        例:>>> s = "xysdls"

             >>> s.find("s")

              2

             >>> s.find("ys")

              1

             >>> s.find("yd")

              -1

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

代码如下:

          

 1 #!/usr/bin/env python
 2 #-*-coding: utf-8-*-
 3 
 4 "idcheck.py -- check the descriptor"
 5 
 6 import string
 7 import keyword
 8 
 9 alphas = string.letters + _    #string.letters返回一个字符串,string.digits也返回一个字符串
10 nums = string.digits
11 alp_nums = alphas + nums
12 keylist = keyword.kwlist
13 
14 print "Welcome to the identifier checker 1.0"
15 
16 while True:
17     my_choice = raw_input("identifier to test?(Y or N): ")
18 
19     if my_choice != "Y" and my_choice != "N":
20         print "please choose Y or N"
21 
22     if my_choice == "N":
23         print "thanks for use! goodbye!"
24         break
25     
26     if my_choice == "Y":
27         get_input = raw_input("Please enter your identifier: ")
28         length = len(get_input)
29 
30         if length == 0:
31             print "Please enter some chars"
32 
33         if length == 1:
34             if get_input not in alphas:
35                 print "invalid identifier: the first char must be alphabetic"
36             elif get_input in keylist:
37                 print "unvalid: It is a keyword"
38             else:
39                 print "Okay as an identifier"
40 
41         if length > 1:
42             firstchar = get_input[0]
43             otherchar = get_input[1:]
44             
45             if get_input in keylist:
46                 print "unvalid: It is a keyword"   
47             elif firstchar not in alphas:
48                 print "invalid: first char must be alphabetic"
49             else:
50                 for eachchar in otherchar:
51                     if eachchar not in alp_nums:
52                         print "invalid: remaining symbols must be alphanumeric"
53                         break
54                 else:
55                     print "Okay as an identifier"
56                 print "Done!"

 6-3. 排序。

       (a)输入一个字符串,并从大到小排序。

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

代码如下:

     a. 按大小排序   

 1 #!/usr/bin/env python
 2 #-*-coding: utf-8-*-
 3 
 4 """a 按大小排序"""
 5 
 6 getInput = raw_input("please enter a list of number: ")
 7 getInput = getInput.split()
 8 
 9 numL = []
10 for eachNum in getInput:
11     eachNum = int(eachNum)
12     numL.append(eachNum)
13 
14 sortL = sorted(numL, reverse = True)
15 for eachNum in sortL:
16     print eachNum,

 

    b. 按字典序排序

 

 1 #!/usr/bin/env python
 2 #-*-coding: utf-8-*-
 3 
 4 """a 按字典序(即ASCII值)排序,sorted对于字符串类型排序用的是字典序"""
 5 
 6 getInput = raw_input("please enter a list of number: ")
 7 getInput = getInput.split()
 8 
 9 sortL = sorted(getInput, reverse=True)
10 
11 for eachNum in sortL:
12     print eachNum,

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

代码如下:

 1 #!/usr/bin/env python
 2 #-*-coding: utf-8-*-
 3 
 4 def test(score):
 5     if score > 100 or score < 0:
 6         return "your input invalid"
 7     if 90 <= score <= 100:
 8         return "A"
 9     if 80 <= score <= 89:
10         return "B"
11     if 70 <= score <= 79:
12         return "C"
13     if 60 <= score <= 69:
14         return "D"
15     if score < 60:
16         return "F"
17 
18 def main():
19     L = []
20     while True:
21         getInput = raw_input("Please enter your score(press ‘q‘ to quit): ")
22         if getInput == q:
23             break
24         getInput = float(getInput)
25         result = test(getInput)
26         if result not in "ABCDF":
27             print result
28         else:
29             print "Your score is %s"  % result
30             L.append(getInput)
31     length = len(L)
32     mean = sum(L) / length
33     print "The mean of your input is %.2f"  % mean
34 
35 if __name__ == __main__:
36     main()

 6-5.字符串。

(a)更新你在2-7里面的方案,使之可以每次向前向后都显示一个字符串的一个字符。

 1 #!/usr/bin/env python
 2 #-*-coding: utf-8-*-
 3 
 4 """#循环和字符串。从用户那里接受一个输入,然后逐个字符显示该字符串。下一次比前一次多一个字符"""
 5 
 6 get_input = raw_input("please enter a string: ")
 7 length = len(get_input)
 8 L = range(1, length + 1)
 9 for i in L:
10     print get_input[:i]
11 print "It‘s done!"
 1 #!/usr/bin/env python
 2 #-*-coding: utf-8-*-
 3 
 4 """#循环和字符串。从用户那里接受一个输入,然后逐个字符显示该字符串。下一次比前一次少一个字符"""
 5 
 6 get_input = raw_input("please enter a string: ")
 7 length = len(get_input)
 8 L = [None] + range(-1, -length, -1)
 9 for i in L:
10     print get_input[:i]
11 print "It‘s done!"

(b)通过扫描来判断两个字符串是否匹配(不能使用比较操作符和cmp()内建函数)

 1 #!/usr/bin/env python
 2 #-*-coding: utf-8-*-
 3 
 4 getInput = raw_input("Please enter two string: ")
 5 getInput = getInput.split()
 6 str1 = getInput[0].lower()
 7 str2 = getInput[1].lower()
 8 len1 = len(str1)
 9 len2 = len(str2)
10 
11 if len1 != len2:
12     print "Not equal!"
13 if len1 == len2:
14     L = range(len1)
15     for i in L:
16         if str1[i] != str2[i]:
17             print "Not equal!"
18             break
19     print "equal!"

 

 

 

 

             

python核心编程(第二版)-------第六章课后习题

原文:http://www.cnblogs.com/aliao-2015-11-18/p/4996369.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!