核心编程答案(第六章)
例6.1
import string def idcheck(myInput): alphas = string.letters + '-' nums = string.digits print 'Testees must be at least 2 chars long.' myInput = raw_input('Identifier to test:') if len(myInput) > 1: if myInput[0] not in alphas: print '''invalid: first symbol must be alphabetic''' else: for otherChar in myInput[1:]: if otherChar not in alphas + nums: print '''invalid: remaining symbol must be alphanumeric' break print 'okay as an identifier'
备注:从性能上来讲,更少的操作可以减少时间,这里“if len(myInput) > 1:”每次都执行判断长度,可以一次性先赋值:stringlen = len(myInput)。这样就可以减少时间了。
6-2
两个方法
str.
find
(sub[, start[, end]])- Return the lowest index in the string where substring sub is found, such that sub is contained in the slice
s[start:end]
. Optional arguments start and end are interpreted as in slice notation. Return-1
if sub is not found.
str.
index
(sub[, start[, end]])- Like
find()
, but raiseValueError
when the substring is not found. - 6-2
- 首先看下keyword具有的方法:
- >>> import keyword
>>> dir(keyword)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'iskeyword', 'kwlist', 'main']
#!/usr/bin/env python # encoding: utf-8 import string import keyword def idcheck(myInput): alphas = string.letters + '_' nums = string.digits if len(myInput) > 1: if myInput[0] not in alphas: print '''invalid: first symbol must be alphabetic''' elif keyword.iskeyword(myInput): print 'is keyword' else: for otherChar in myInput[1:]: if otherChar not in alphas + nums: print '''invalid: remaining symbol must be alphanumeric''' break print 'ok as an Identifier' else: if len(myInput) == 1: if myInput[0] not in alphas: print '''invalid: remaining symbol must be alphanumeric''' else: print 'ok as an Identifier' if __name__ == "__main__": myInput = raw_input('Enter a string:') idcheck(myInput
6-8
这里没考虑为10开头的,还有几个地方显示不好的,比如100。
#!/usr/bin/env python # encoding: utf-8 enlist = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "zero", "one hundred", "two hundred", "three hundred", "four hundred", "five hundred", "six hundred", "seven hundred", "eight hundred", "nine hundred"] num_str = raw_input('Enter a number: ') numlen = len(num_str) enexpress = "" for i in range(numlen - 1, -1, -1): # 从大到小 enexpress = enexpress + "-" + enlist[int(num_str[numlen - 1 - i]) + 10 * i] # 直接从列表中读出 enexpress = enexpress.strip("-") print enexpress
6-10
#!/usr/bin/env python # encoding: utf-8 import string def Str_inverted(input_str): len_str = len(input_str) ch_str = '' for i in range(len_str): if input_str[i] in string.ascii_lowercase: ch_str = ch_str + input_str[i].upper() elif input_str[i] in string.ascii_uppercase: ch_str = ch_str + input_str[i].lower() else: ch_str = ch_str + input_str[i] return ch_str if __name__ == "__main__": input_str = raw_input('enter a str: ') print Str_inverted(input_str)
另外,可以直接使用swapcase(),一步到位。所以要熟悉基本的函数方法标准库
6-11
思路:整数转换为二进制,八位二进制代表一位地址。
a、b
#!/usr/bin/env python # encoding: utf-8 import ipdb def int_ip(intnum): # ipdb.set_trace() str_bin = bin(intnum) bin_len = len(str_bin) if 26 < bin_len <=34: # 因为bin()前面会多出0b,所以要多出两位 ip1 = str(eval(str_bin[:-24])) ip2 = str(eval('0b' + str_bin[-24:-16])) ip3 = str(eval('0b' + str_bin[-16:-8])) ip4 = str(eval('0b' + str_bin[-8:])) return ip1 + '.' + ip2 + '.' + ip3 + '.' + ip4 elif 18 < bin_len <=26: ip1 = str('0') ip2 = str(eval(str_bin[:-16])) ip3 = str(eval('0b' + str_bin[-16:-8])) ip4 = str(eval('0b' + str_bin[-8:])) return ip1 + '.' + ip2 + '.' + ip3 + '.' + ip4 elif 10 < bin_len <=18: ip1 = str('0') ip2 = str('0') ip3 = str(eval(str_bin[:-8])) ip4 = str(eval('0b' + str_bin[-8:])) return ip1 + '.' + ip2 + '.' + ip3 + '.' + ip4 elif bin_len <=10: ip1 = str('0') ip2 = str('0') ip3 = str('0') ip4 = str(eval(str_bin)) return ip1 + '.' + ip2 + '.' + ip3 + '.' + ip4 else: return 'Out of range! ' def ip_to_int(ip_input): ipdb.set_trace() ip_list = ip_input.split('.') ip_int = int(ip_list[0]) * (256**3) + int(ip_list[1]) * (256 ** 2) + int(ip_list[2]) *256 + int(ip_list[3]) return ip_int if __name__ == "__main__": intnum = int(raw_input("Enter a int number: ")) print int_ip(intnum) ip_input = raw_input('Enter ip: ') print ip_to_int(ip_input)
6-12
a、思路:先判断在不在里面,在的话,使用for来判定位置
def findchr(string, char): if char in string: strindex = [] string_len = len(string) char_len = len(char) for i in range(string_len): if string[i:i + char_len] == char: strindex.append(i) return strindex else: return -1 if __name__ == "__main__": string = raw_input('Enter a string: ') char = raw_input('enter a char: ') print findchr(string, char)
6-14
思路:应用字典作全部例举,将输入直接作为键值,返回值。
import random def Rochambeau(str_input): str_list = ['shitou', 'jiandao', 'bu'] random_str = random.choice(str_list) cmp_dict = {'shitoujiandao': '1', 'shitoushitou': '0', 'shitoubu': '-1', 'jiandaojiandao': '0', 'jiandaoshitou': '-1', 'jiandaobu': '1', 'bujiandao': '-1', 'bushitou': '1', 'bubu': '0'} num_mean = {'1': 'you are win!', '0': 'draw!', '-1': 'you are losed!'} if str_input in str_list: cmp_str = str_input + random_str return "machin is '%s'" % random_str + '\n' + num_mean[cmp_dict[cmp_str]] else: return "please enter 'shihtou','jiandao','bu'" if __name__ == "__main__": str_input = raw_input('Enter a string: ') print Rochambeau(str_input)