第六章-序列:字符串、列表和元组 课后答案

6-1

成员操作符in可以判断一个字符串是否是另一个字符串的一部分。返回true或false。

6-2

 1 import string
 2 import keyword
 3 
 4 myInput = raw_input("Please input the string: ")
 5 
 6 if len(myInput) == 1:
 7     if myInput in string.ascii_letters or myInput == '_':
 8         print "right,the length of this identifier is 1"
 9     else:
10         print "is not a identifier"
11 elif len(myInput) > 1:
12     if myInput in keyword.kwlist:
13         print "%s is a keyword of Python" % myInput
14     else:
15         print "is not a keyword"

6-3

 1 #从大大小排列
 2 def new_sort1(strNum):
 3     num = []
 4     num = strNum.split(" ")
 5     num.sort()
 6     return list(reversed(num))
 7 #用字典序从小到大排列
 8 def new_sort2(strNum):
 9     num = []
10     num = strNum.split(" ")
11     num = sorted([int(x) for x in num])
12     return list(reversed(num))    
13 
14 if __name__ == "__main__":
15     strNum = raw_input("please enter the numbers:")
16     print "after sorted, the number is:"
17     print new_sort1(strNum)
18     print new_sort2(strNum)

6-4

 1 def score_test(score_num):
 2     nlist = []
 3     nlist = score_num.split(" ")
 4     sum = 0
 5     for x in nlist:
 6         sum += float(x)
 7     return sum/len(nlist)
 8 
 9 num = raw_input("Please input the numbers: ")
10 print score_test(num)

6-5

 1 def showStr(strTemp):
 2     try:
 3         num = []
 4         length = len(strTemp)
 5         for i in range(length // 2):
 6             num.append(strTemp[i])
 7             num.append(strTemp[length - i - 1])
 8     except IndexError:
 9         pass
10     finally:
11         if length % 2 == 1:
12             num.append(strTemp[length // 2])
13         return num
14 
15 if __name__ == "__main__":
16     while True:
17         strTemp = raw_input("please enter the string(-1 to quit):")
18         if strTemp == "-1":
19             break
20         print "the strange string is:"
21         print showStr(strTemp)

6-6

 1 def myStrip(mystring):
 2     mList = list(mystring)
 3     while mList[0] == " ":
 4         del mList[0]
 5     while mList[len(mList)-1] == " ":
 6         del mList[len(mList)-1]
 7     print "".join(mList)
 8 
 9 mstr = raw_input("Please input the string:")
10 myStrip(mstr)

6-7

看的pdf打印版有些模糊,程序没有缩进,在这儿只写答案

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 #程序目的:所求数除以1到所求数的任意数,能除尽的被剔除掉
 4 #输入所求数
 5 num_str = raw_input("Enter a number:")
 6 
 7 #字符串转化为int数据类型
 8 num_num = int(num_str)
 9 
10 #除数的范围:1到所求数
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     #判断能否被除尽
21     if num_num % fac_list[i] == 0:
22         del fac_list[i]
23     else:
24         i = i + 1
25 
26 #输出
27 print "ATTER:", fac_list

6-8

 1 dict1 = {"1":"one","2":"two","3":"three","4":"four","5":"five",
 2          "6":"six","7":"seven","8":"eight","9":"nine","0":""}
 3 dict2 = {"1":"ten","2":"twenty","3":"thirty","4":"fourty","5":"fifty",
 4          "6":"sixty","7":"seventy","8":"eighty","9":"ninety","0":""}
 5 dict3 = {"1":"one-hundred","2":"two-hundred","3":"three-hundred","4":"four-hundred","5":"five-hundred",
 6          "6":"six-hundred","7":"seven-hundred","8":"eight-hundred","9":"nine-hundred","0":""}
 7 dictAll = {1:dict1, 2:dict2, 3:dict3}
 8 def fun1(strNum):
 9     if int(strNum) > 1000 or int(strNum) < 0:
10         return "error number"
11     length = len(strNum)
12     strTemp = ""
13     if length == 4:
14         strTemp = "one thousand "
15         return strTemp
16     for i in range(length):
17         if strNum[i] == "0":
18             strTemp += dictAll[length - i][strNum[i]]
19         else:
20             strTemp += dictAll[length - i][strNum[i]] + "-"
21     strTemp = strTemp[0:-1]
22     return strTemp
23 if __name__ == "__main__":
24     while True:
25         strNum = raw_input("please enter the num(q to quit):")
26         if strNum.lower() == "q":
27             break
28         print "the num is: %s" % (fun1(strNum))

 6-9

def convert(strMin):
    hour, minute = divmod(int(strMin), 60)
    return hour, minute

6-10

1 import string
2 def convert(strTemp):
3     sList = list(strTemp)
4     for i in range(len(sList)):
5         if sList[i] in string.lowercase:
6             sList[i] = sList[i].upper()
7         elif sList[i] in string.uppercase:
8             sList[i] = sList[i].lower()
9     return "".join(sList)

6-11

 1 #整数到IP地址
 2 def tranFromIntToIP(strInt):
 3     ip1 = 0
 4     ip2 = 0
 5     ip3 = 0
 6     ip4 = 0
 7     ip1 = int(strInt) / (256 ** 3)
 8     ip2 = (int(strInt) % (256 ** 3)) / (256 ** 2)
 9     ip3 = (int(strInt) % (256 ** 2)) / 256
10     ip4 = int(strInt) % 256
11     return str(ip1) + "." + str(ip2) + "." + str(ip3) + "." + str(ip4)
12 #IP地址到整数
13 def tranFromIPToInt(strIP):
14     lst = strIP.split(".")
15     if len(lst) != 4:
16         return "error ip"
17     return int(lst[0]) * (256 ** 3) + int(lst[1]) * (256 ** 2) + int(lst[2]) * 256 + int(lst[3])

6-12

 1 def findchr(string, char):
 2     length = len(string)
 3     for i in range(length):
 4         if string[i] == char:
 5             return i
 6     return -1
 7 
 8 def rfindchr(string, char):
 9     length = len(string)
10     for i in range(length):
11         if string[length - i - 1] == char:
12             return length - i - 1
13     return -1
14 
15 def subchr(string, origchar, newchar):
16     length = len(origchar)
17     largeLength = len(string)
18     newstring = ""
19     i = 0
20     while i < largeLength:
21         if string[i:i + length] == origchar:
22             newstring += newchar
23             i += length
24         else:
25             newstring += string[i]
26             i += 1
27     return newstring

 6-13

1 def atoc(strComplex):
2     i = 0
3     length = len(strComplex)
4     while i < length:
5         if strComplex[length - i - 2] in ["+","-"]:
6             return complex(float(strComplex[0:length - i - 2]), float(strComplex[length - i - 2:length - 1]))
7         else:
8             i += 1

6-14

1 import random
2 def Rochambeau(string):
3     if string != "stone" and string != "shears" and string != "cloth":
4         return "input error!"
5     myDict = {"stone":"1","shears":"2","cloth":"3"}
6     allDict = {"12":"win","23":"win","31":"win","11":"equal","22":"equal","33":"equal","13":"lose","21":"lose","32":"lose"}
7     rNum = random.randrange(1, 4)
8     return "you are %s!!!" % allDict[myDict[string]+str(rNum)]

6-15

 1 import datetime
 2 def interval(time1, time2):
 3     t1 = time1.split("/")
 4     t2 = time2.split("/")
 5     return datetime.date(int(t1[0]), int(t1[1]), int(t1[2])) - datetime.date(int(t2[0]), int(t2[1]), int(t2[2]))
 6 
 7 def birthday(bir):
 8     myList = bir.split("/")
 9     birth = datetime.date(int(myList[0]), int(myList[1]), int(myList[2]))
10     today = datetime.date.today()
11     return today - birth
12 
13 def nextBir(bir):
14     myList = bir.split("/")
15     birth = datetime.date(int(myList[0]), int(myList[1]), int(myList[2]))
16     today = datetime.date.today()
17     new_birth = birth.replace(year = today.timetuple().tm_year)
18     if new_birth < today:
19         new_birth = Birth.replace(year = today.tm_year + 1)
20     return new_birth - today

 6-16

 1 # -*- coding: utf-8 -*-
 2 def Add(lst1, lst2):
 3     """矩阵的加法"""
 4     row = len(lst1)
 5     col = len(lst1[0])
 6     for i in range(row):
 7         for j in range(col):
 8             lst1[i][j] += lst2[i][j]
 9     return lst1
10 def MulLst(lst1, lst2):
11     """将两个列表进行相乘"""
12     length = len(lst1)
13     num = 0
14     for i in range(length):
15         num += lst1[i] * lst2[i]
16     return num
17 def chanLst(lst):
18     """将矩阵反转,只为更好的计算矩阵的乘法"""
19     row = len(lst)
20     col = len(lst[0])
21     num = []
22     subNum = []
23     for i in range(col):
24         for j in range(row):
25             subNum.append(lst[j][i])
26         num.append(subNum)
27         subNum = []
28     return num
29 def Mul(lst1, lst2):
30     """两个矩阵进行相乘"""
31     lst2 = chanLst(lst2)
32     num = []
33     subNum = []
34     row1 = len(lst1)
35     row2 = len(lst2)
36     for i in range(row1):
37         for j in range(row2):
38             subNum.append(MulLst(lst1[i] , lst2[j]))
39         num.append(subNum)
40         subNum = []
41     return num

6-17

1 def myPop(lst):
2     lst = lst[:-1]
3     return lst

6-18

元组

原文地址:https://www.cnblogs.com/hell0x/p/5139482.html