您所在的位置:小祥子 » 编程 » Python » 正文

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

时间:2015-08-03 编辑:snvs 来源:CnBlogs

6–6. 字符串.创建一个 string.strip()的替代函数:接受一个字符串,去掉它前面和后面的 空格(如果使用 string.*strip()函数那本练习就没有意义了) 

 'Take a string and remove all leading and trailing whitespace'
 
 def newStrip(str):
     'delete blanks around a string'
     _end = len(str)
     _start = 0
     
     # delete the blanks at the beginning of the string
     for i in range(_end):
         if str[i] != ' ':
             _start = i
             break              
     else:
         print 'invalid: The string is a blank string.'     # if the string is a 
         _blank = True                                      # blank string
         
     
     # delete the blanks in the end of the string
     for i in range(-1, _start - _end, -1):
         if str[i] != ' ':
             _end = _end + i
             break      
     if not _blank:
         print '-' + str[_start: _end] + '-'   # print '-' make sure the function work
 
 # test
 if __name__ == '__main__':
     newStrip(raw_input('Enter a string: '))

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 中。代码如下:

 # get a number input from the user
 num_str = raw_input('Enter a number: ')
 
 # change the number(type of str) to a integer
 num_num = int(num_str)
 
 # make a list range of [1, num_num]
 fac_list = range(1, num_num + 1)
 print 'BEFORE:', repr(fac_list)  # the book use '', but I think it is wrong
 
 # set a variable to start a loop
 i = 0
 fac_list_new = []
 # make a while loop
 while i < len(fac_list):
 
     # del all the common divisors of num_num and numbers less then it
     if num_num % fac_list[i] != 0:
         fac_list_new.append(fac_list[i])
     # add i to continue loop
     i = i + 1
 
 # print the result
 print 'AFTER:', repr(fac_list_new)

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

 """
 Given an integer value, return a string with the equivalent English text of each digit. 
 For example, an input of 89 results in "eight-nine" being returned.
 """
 
 def num2eng(num):
     '''change num to english'''
 
     # set a dictionary of num and English text
     n2e = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
         6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}
     
     # set a blank list to put english text into it
     numList = []
     
     # for each num, get its english name and append it into the blank list
     for i in range(len(num)):
         numList.append(n2e[int(num[i])])
     
     # print the result
     print '-'.join(numList)
 
 # test
 if __name__ == '__main__':
     num2eng(raw_input('Enter a number: '))

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

 '''
 take the total number of minutes 
 and return the same time interval in hours and minutes
 '''
 
 def clock(minutes):
     'change time of minutes to hours and minutes'
     
     hours = minutes / 60
     minutes_left = minutes % 60
     print '%d minute(s) is %d hour(s) and %d minute(s)' \
                                 % (minutes, hours, minutes_left)
 
 # test
 if __name__ == '__main__':
     clock(int(raw_input('Enter minutes: ')))

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

 '''
 Create a function that will return another string similar to the input string, 
 but with its case inverted. 
 For example, input of "Mr. Ed" will result in "mR. eD" as the output string.
 '''
 import string
 uppercase = string.ascii_uppercase
 lowercase = string.ascii_lowercase
 
 def CaseInvert(str):
     
     # make a blank list to store the changed character
     _list = []
 
     for i in str:
         
         # uppercase to lowercase
         if i in uppercase:
             i = i.lower()
 
         # lowercase to uppercase
         elif i in lowercase:
             i = i.upper()
         
         _list.append(i)
 
     print ''.join(_list)
 
 # test
 if __name__ == '__main__':
     CaseInvert(str = raw_input('Enter a string: '))

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

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

 '''
 Create a program that will convert from an integer to 
 an Internet Protocol (IP) address in the four-octet format of 
 WWW.XXX.YYY.ZZZ.
 Or to do the vice versa of the above.
 '''
 
 def num2IP(num):
     'convert number to IP'
     IPlist = [num[i : i + 3] for i in (0, 3, 6, 9)]
     print '.'.join(IPlist)
 
 def IP2num(IP):
     'convert IP to num'
     numlist = IP.split('.')
     print ''.join(numlist)
 
 def showchoice():
     'choose the direction of convertion'
     text = '''
 Enter 'n' to convert num to IP
 Enter 'i' to convert IP to num
 Enter anything else to quit
 '''
     funcdict = {'n': num2IP, 'i': IP2num}
     while True:
         _input = raw_input(text)
         
         # choose a function use a dictionary
         if _input == 'n' or _input == 'i':
             funcdict[_input](raw_input('> '))
         else:
             break
 # test
 if __name__ == '__main__':
     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()类似,不同的是,如果找到匹配的字符就用新的字符替换原先字符.返回 修改后的字符串. 

 def findchr(string, char):
     '''findchr() will look for character char in string and 
     return the index of the first occurrence of char, 
     or -1 if that char is not part of string.'''
     if char not in string:
         return -1
     else:
         leng_str = len(string)
         leng_chr = len(char)
         for i in range(leng_str - leng_chr + 1):
             if string[i : i + leng_chr] == char:
                 return i
                 break
 
 
 def rfindchr(string, char):
     'rfindchr() that will find the last occurrence of a character in a string.'
     if char not in string:
         return -1
     else:
         leng_str = len(string)
         leng_chr = len(char)
         for i in range(leng_str - leng_chr + 1):
             if string[i : i + leng_chr] == char:
                 _index = i
         else:
             print _index
                
 def subchr(string, origchar, newchar):
     '''
     subchr() is similar to findchr() except that whenever origchar is found, 
     it is replaced by newchar. 
     The modified string is the return value.
     '''
     if origchar not in string:
         return -1
     else:
         leng_str = len(string)
         leng_chr = len(origchar)
         for i in range(leng_str - leng_chr + 1):
             if string[i : i + leng_chr] == origchar:
                 string = string[:i] + newchar + string[i + leng_chr :]
                 return string
                 break
 
 # test
 if __name__ == '__main__':
     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 都必须是浮点值. 

 '''
 convert strings to complex
 e.g., '- 1.23e+4-5.67j'
 '''
 import re
 
 def atoc(_str):
     'comvert strings to complex'
     if 'j' not in _str:
         return complex(float(_str))
     else:
         _str_no_blank = ''.join(_str.split())
         comlist = _str_no_blank.split('j')
         if '' not in comlist:
             return complex(float(comlist[1]), float(comlist[0]))
         else:
             length = len(_str)
             _index = 0
             for i in range(-1, -length, -1):
                 if _str[i] in ('+', '-'):
                     _index = i
                     break
             return complex(float(_str[:_index]), float(_str[_index:-1]))
 
 if __name__ == '__main__':
     print atoc(raw_input('Enter a integer: '))

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

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

(b)石头砸剪子,

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

 '''
 a "rock, paper, scissors" game, 
 
 a.the paper covers the rock,
 b.the rock breaks the scissors,
 c.the scissors cut the paper.
 '''
 
 import random
 
 def rochambeau():
     'a "rock, paper, scissors" game'
     
     # get user's input and convert it to a number
     rochdic = {'r':0, 'p': 1, 's': 2}
     u_choice = raw_input('''Enter your choice:
         r for rock
         p for paper
         s for scissors:
         ''')
     c_choice = random.randrange(3)
     
     # the difference between user's choice and computer's choice
     result = rochdic[u_choice] - c_choice
     if result == 0:
         print 'You draw with computer!'
     elif result == -1 or result == 2:
         print 'You lose!'
     else:
         print 'You win!'
 
 # test
 if __name__ == '__main__':
     rochambeau()

6–15.转换

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

 '''
 Given a pair of dates in some recognizable standard format such as MM/DD/YY or DD/MM/YY, 
 determine the total number of days that fall between both dates.
 '''
 
 def dateofyear():
     'calculate the total number of days between two dates'
     date1 = raw_input('Enter a date of MM/DD/YYYY: ')
     date2 = raw_input('Enter another date of MM/DD/YYYY: ')
     if date1[-4: -1] > date2[-4 : -1]:
         date1, date2 = date2, date1
     datelist = [date1, date2]
     daylist = [0, 0]
     yearlist = [0, 0]
     monthlist = [0, 0]
     for i in (0, 1):
         (m, d, y) = [int(item) for item in datelist[i].split('/')]
         print (m, d, y)
         yearlist[i] = y
         monthlist[i] = m
         if m == 2:
             month_days = 28
         elif m in (4, 6, 9, 11):
             month_days = 30
         else:
             month_days = 31
         daylist[i] = 365* y + month_days * m + d
     leapyear = 0
     for year in range(yearlist[0], yearlist[1] + 1):
         if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
             leapyear += 1
 
         if monthlist[0] >= 3:
             leapyear -= 1
         if monthlist[1] < 3:
             leapyear -= 1
 
     days = daylist[1] - daylist[0] + leapyear
     print days
 
 if __name__ == '__main__':
     dateofyear()
关键词:python 编程