python第六章课后题答案_python 核心编程第六章课后题自己做的答案

6–7. 调试.看一下在例 6.5 中给出的代码(buggy.py)

(a)研究这段代码并􏰀述这段代码想做什么.在所有的(#)处都要填写你的注释.

(b)这个程序有一个很大的问题,比如输入 6,12,20,30,等它会死掉,实际上它不能处理任何的偶

数,找出原因.

(c)修正(b)中􏰁出的问题.

我的解答:

(a)这段代码是要用户输入一个数字,然后输出所有不能整除这个数字的数字

(b)因为每次删除后,删除的元素后的元素位置就提前了一位,删除了1后,2就变成了第一个,而循环的下一个是 fac_list[1] ,所以不会删除2. 而后边的可整除的数之间间隔大于1,所以不受影响,不过感觉这样写的代码不好。

(c)我的解决方法是建立一个空的列表 fac_list_new, 每当 fac_list 中有不能整除的数就添加到 fac_list_new 中。代码如下:

1 #get a number input from the user

2 num_str = raw_input('Enter a number:')3

4 #change the number(type of str) to a integer

5 num_num =int(num_str)6

7 #make a list range of [1, num_num]

8 fac_list = range(1, num_num + 1)9 print 'BEFORE:', repr(fac_list) #the book use '', but I think it is wrong

10

11 #set a variable to start a loop

12 i =013 fac_list_new =[]14 #make a while loop

15 while i

17 #del all the common divisors of num_num and numbers less then it

18 if num_num % fac_list[i] !=0:19 fac_list_new.append(fac_list[i])20 #add i to continue loop

21 i = i + 1

22

23 #print the result

24 print 'AFTER:', repr(fac_list_new)

6–8. 列表.给出一个整数值,返回代表该值的英文,比如输入 89 返回"eight-nine"。

1 """

2 Given an integer value, return a string with the equivalent English text of each digit.3 For example, an input of 89 results in "eight-nine" being returned.4 """

5

6 defnum2eng(num):7 '''change num to english'''

8

9 #set a dictionary of num and English text

10 n2e = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',11 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}12

13 #set a blank list to put english text into it

14 numList =[]15

16 #for each num, get its english name and append it into the blank list

17 for i inrange(len(num)):18 numList.append(n2e[int(num[i])])19

20 #print the result

21 print '-'.join(numList)22

23 #test

24 if __name__ == '__main__':25 num2eng(raw_input('Enter a number:'))

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

1 '''

2 take the total number of minutes3 and return the same time interval in hours and minutes4 '''

5

6 defclock(minutes):7 'change time of minutes to hours and minutes'

8

9 hours = minutes / 60

10 minutes_left = minutes % 60

11 print '%d minute(s) is %d hour(s) and %d minute(s)'\12 %(minutes, hours, minutes_left)13

14 #test

15 if __name__ == '__main__':16 clock(int(raw_input('Enter minutes:')))

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

1 '''

2 Create a function that will return another string similar to the input string,3 but with its case inverted.4 For example, input of "Mr. Ed" will result in "mR. eD" as the output string.5 '''

6 importstring7 uppercase =string.ascii_uppercase8 lowercase =string.ascii_lowercase9

10 defCaseInvert(str):11

12 #make a blank list to store the changed character

13 _list =[]14

15 for i instr:16

17 #uppercase to lowercase

18 if i inuppercase:19 i =i.lower()20

21 #lowercase to uppercase

22 elif i inlowercase:23 i =i.upper()24

25 _list.append(i)26

27 print ''.join(_list)28

29 #test

30 if __name__ == '__main__':31 CaseInvert(str = raw_input('Enter a string:'))

6–11.转换

(a)创建一个从整数到 IP 地址的转换程序,如下格式: WWW.XXX.YYY.ZZZ.

(b)更新你的程序,使之可以逆转换.

1 '''

2 Create a program that will convert from an integer to3 an Internet Protocol (IP) address in the four-octet format of4 WWW.XXX.YYY.ZZZ.5 Or to do the vice versa of the above.6 '''

7

8 defnum2IP(num):9 'convert number to IP'

10 IPlist = [num[i : i + 3] for i in (0, 3, 6, 9)]11 print '.'.join(IPlist)12

13 defIP2num(IP):14 'convert IP to num'

15 numlist = IP.split('.')16 print ''.join(numlist)17

18 defshowchoice():19 'choose the direction of convertion'

20 text = '''

21 Enter 'n' to convert num to IP22 Enter 'i' to convert IP to num23 Enter anything else to quit24 '''

25 funcdict = {'n': num2IP, 'i': IP2num}26 whileTrue:27 _input =raw_input(text)28

29 #choose a function use a dictionary

30 if _input == 'n' or _input == 'i':31 funcdict[_input](raw_input('>'))32 else:33 break

34 #test

35 if __name__ == '__main__':36 showchoice()

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()类似,不同的是,如果找到匹配的字符就用新的字符替换原先字符.返回 修改后的字符串.

1 deffindchr(string, char):2 '''findchr() will look for character char in string and3 return the index of the first occurrence of char,4 or -1 if that char is not part of string.'''

5 if char not instring:6 return -1

7 else:8 leng_str =len(string)9 leng_chr =len(char)10 for i in range(leng_str - leng_chr + 1):11 if string[i : i + leng_chr] ==char:12 returni13 break

14

15

16 defrfindchr(string, char):17 'rfindchr() that will find the last occurrence of a character in a string.'

18 if char not instring:19 return -1

20 else:21 leng_str =len(string)22 leng_chr =len(char)23 for i in range(leng_str - leng_chr + 1):24 if string[i : i + leng_chr] ==char:25 _index =i26 else:27 print_index28

29 defsubchr(string, origchar, newchar):30 '''

31 subchr() is similar to findchr() except that whenever origchar is found,32 it is replaced by newchar.33 The modified string is the return value.34 '''

35 if origchar not instring:36 return -1

37 else:38 leng_str =len(string)39 leng_chr =len(origchar)40 for i in range(leng_str - leng_chr + 1):41 if string[i : i + leng_chr] ==origchar:42 string = string[:i] + newchar + string[i +leng_chr :]43 returnstring44 break

45

46 #test

47 if __name__ == '__main__':48 subchr(string = raw_input('Enter a string:'), origchar = raw_input('Enter another string:'), newchar = '---')

6–13.字符串.string 模块包含三个函数,atoi(),atol(),和 atof(),它们分别负责把字符串转 换成整数,长整型,和浮点型数字.从 Python1.5 起,Python 的内建函数 int(),long(),float()也可以 做相同的事了, complex()函数可以把字符串转换成复数.(然而 1,5 之前,这些转换函数只能工作于 数字之上)

string 模块中并没有实现一个 atoc()函数,那么你来实现一个,atoc(),接受单个字符串做参 数输入,一个表示复数的字符串,例如,'-1.23e+4-5.67j',返回相应的复数对象.你不能用 eval()函 数,但可以使用 complex()函数,而且你只能在如下的限制之下使用 complex():complex(real,imag)

的 real 和 imag 都必须是浮点值.

1 '''

2 convert strings to complex3 e.g., '- 1.23e+4-5.67j'4 '''

5 importre6

7 defatoc(_str):8 'comvert strings to complex'

9 if 'j' not in_str:10 returncomplex(float(_str))11 else:12 _str_no_blank = ''.join(_str.split())13 comlist = _str_no_blank.split('j')14 if '' not incomlist:15 return complex(float(comlist[1]), float(comlist[0]))16 else:17 length =len(_str)18 _index =019 for i in range(-1, -length, -1):20 if _str[i] in ('+', '-'):21 _index =i22 break

23 return complex(float(_str[:_index]), float(_str[_index:-1]))24

25 if __name__ == '__main__':26 print atoc(raw_input('Enter a integer:'))

6–14.随机数.设计一个"石头,剪子,布"游戏,有时又叫"Rochambeau",你小时候可能玩过,下面 是规则.你和你的对手,在同一时间做出特定的手势,必须是下面一种手势:石头,剪子,布.胜利者从 下面的规则中产生,这个规则本身是个悖论.

(a) the paper covers the rock, 布包石头.

(b)石头砸剪子,

(c)剪子剪破布.在你的计算机版本中,用户输入她/他的选项,计算机找一个随机选项,然后由你 的程序来决定一个胜利者或者平手.注意:最好的算法是尽量少的使用 if 语句.

1 '''

2 a "rock, paper, scissors" game,3

4 a.the paper covers the rock,5 b.the rock breaks the scissors,6 c.the scissors cut the paper.7 '''

8

9 importrandom10

11 defrochambeau():12 'a "rock, paper, scissors" game'

13

14 #get user's input and convert it to a number

15 rochdic = {'r':0, 'p': 1, 's': 2}16 u_choice = raw_input('''Enter your choice:17 r for rock18 p for paper19 s for scissors:20 ''')21 c_choice = random.randrange(3)22

23 #the difference between user's choice and computer's choice

24 result = rochdic[u_choice] -c_choice25 if result ==0:26 print 'You draw with computer!'

27 elif result == -1 or result == 2:28 print 'You lose!'

29 else:30 print 'You win!'

31

32 #test

33 if __name__ == '__main__':34 rochambeau()

6–15.转换

给出两个可识别格式的日期,比如 MM/DD/YY 或者 DD/MM/YY 格式,计算出两个日期间的天 数.

1 '''

2 Given a pair of dates in some recognizable standard format such as MM/DD/YY or DD/MM/YY,3 determine the total number of days that fall between both dates.4 '''

5

6 defdateofyear():7 'calculate the total number of days between two dates'

8 date1 = raw_input('Enter a date of MM/DD/YYYY:')9 date2 = raw_input('Enter another date of MM/DD/YYYY:')10 if date1[-4: -1] > date2[-4 : -1]:11 date1, date2 =date2, date112 datelist =[date1, date2]13 daylist =[0, 0]14 yearlist =[0, 0]15 monthlist =[0, 0]16 for i in (0, 1):17 (m, d, y) = [int(item) for item in datelist[i].split('/')]18 print(m, d, y)19 yearlist[i] =y20 monthlist[i] =m21 if m == 2:22 month_days = 28

23 elif m in (4, 6, 9, 11):24 month_days = 30

25 else:26 month_days = 31

27 daylist[i] = 365* y + month_days * m +d28 leapyear =029 for year in range(yearlist[0], yearlist[1] + 1):30 if year % 4 == 0 and year % 100 != 0 or year % 400 ==0:31 leapyear += 1

32

33 if monthlist[0] >= 3:34 leapyear -= 1

35 if monthlist[1] < 3:36 leapyear -= 1

37

38 days = daylist[1] - daylist[0] +leapyear39 printdays40

41 if __name__ == '__main__':42 dateofyear()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值