python核心编程第6章习题答案
来源:互联网 发布:主机监控软件 编辑:程序博客网 时间:2024/06/05 17:57
3:
(1):学习一下第3行的用法
num=raw_input("enter all the num and split with space:").split()num=[int(eachStr) for eachStr in num]#学习一下这种用法sortedList=sorted(num)[::-1]print sortedList
结果:
enter all the num and split with space:1 44 23 99 112[112, 99, 44, 23, 1]
(2):
字典序:字典排列字符串是比较首字符的ASCII码的,如果一样则比较第二个字符,直到有一方胜出,如果长度不一样的话,则字符串较长的那个值大!
num=raw_input("enter all the num and split with space:").split()sortedList=sorted(num)[::-1]print sortedList
结果:
enter all the num and split with space:1 90 104 23 44['90', '44', '23', '104', '1']
5
(a):
inStr=raw_input("enter the str:")strlen=len(inStr)if strlen%2==0: for i in range(strlen/2): print (inStr[i],inStr[strlen-1-i])else: for i in range(strlen/2+1): print (inStr[i],inStr[strlen-1-i])
(c):
inStr=raw_input("enter the str:")strlen=len(inStr)flag=Truefor i in range(strlen/2): if inStr[i]!=inStr[strlen-1-i]: flag=Falseif flag==True: print "yes"else: print "no"
6,
我用了个超蠢的方法,如下:
# -*- coding: utf-8 -*-"""Created on Tue Nov 01 17:19:59 2016@author: yangJirui"""theStr = raw_input("enter the string:")print repr(theStr)str_len = len(theStr)start = 0end = str_lenfor i in range(str_len - 1): if theStr[0] != ' ': break elif theStr[i] == ' ' and theStr[i+1] != ' ': start = i + 1 breakfor i in range(1,str_len)[::-1]: if theStr[-1] != ' ': break elif theStr[i] == ' ' and theStr[i - 1] != ' ': end = i breakif theStr.count(' ') == str_len: start = 0 end = 0theStr = theStr[start:end]print repr(theStr)
结果:
enter the string: d dd ddd ddd ' d dd ddd ddd ''d dd ddd ddd'
博客【1】的方法不错,贴一下:
def del_space(str): str = list(str) i = 0 lenth = len(str) while str[0] == ' ': str.pop(0) while str[-1] == ' ': str.pop() return ''.join(str)if __name__ == "__main__": while True: string = raw_input('Enter a string("q" to quit):') if string == "q": break else: print del_space(string)
7
修改后为:
inStr=raw_input("enter the str:")num=int(inStr)numList=range(1,num)newList=numList[:]print numListfor i in numList: if num % i==0: del newList[newList.index(i)]print newListprint numList
结果:
enter the str:12[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11][5, 7, 8, 9, 10, 11][1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
8
def num99Trans(num): nameList = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen'] numList = range(14) finalName = "erro" if num <= 13: # deal special name finalName = nameList[numList.index(num)] elif num <= 99: numTuple = (shiWei, geWei) = divmod(num, 10) nameList[0] = '' if shiWei == 1: if geWei == 5: finalName = 'fifteen' else: finalName = nameList[numList.index(geWei)] + 'teen' elif shiWei == 2: finalName = 'twenty ' + nameList[numList.index(geWei)] elif shiWei == 3: finalName = 'thirty ' + nameList[numList.index(geWei)] elif shiWei == 5: finalName = 'fifty ' + nameList[numList.index(geWei)] else: finalName = nameList[numList.index(shiWei)] + 'ty ' + nameList[numList.index(geWei)] else: print 'over 100 in num99Trans' return finalNamedef num1000Trans(num): nameList=('','one','two','three','four','five','six','seven','eight','nine','ten','eleven', 'twelve','thirteen') numList = range(14) finalName="erro" if 100<=num<=999: (baiWei,shiGeWei)=divmod(num,100) (shiWei,geWei)=divmod(shiGeWei,10) if shiWei==0: finalName=nameList[ numList.index(baiWei)]+' hundred and '+nameList[ numList.index(geWei) ] else: finalName=nameList[ numList.index(baiWei)]+' hundred '+num99Trans(shiGeWei) elif num==1000: finalName='one thusand' else: print 'over 1000 in num1000Trans' return finalNameif __name__=='__main__': num = int(raw_input("enter the num::")) if num<100: print num99Trans(num) elif num<=1000: print num1000Trans(num) else: print"num is too large or small"
9
def transM2H(minutes): (hours,minutes)=divmod(minutes,60) while minutes>60: templeHour,mniutes=divmod(mniutes,60) hours+=templeHour return (hours,minutes)if __name__=='__main__': minutes = int(raw_input('enter the minutes::')) print "hours:%d,minutes:%d" % transM2H(minutes)
10
def trans(instr): return instr.swapcase()def myTrans(instr): instrList=list(instr) i=0 for data in instrList: if 'a'<=data<='z': instrList[i]=data.upper() elif 'A'<=data<='Z': instrList[i]=data.lower() i+=1 return ''.join(instrList)if __name__=='__main__': instr=raw_input("enter the string::") print repr(instr) print repr( myTrans(instr) ) # print repr(trans(instr))
11
# -*- coding: utf-8 -*-def int2ip(num): binaryNumList=32*[0] if num==0: return '0.0.0.0' i=-1 while num>0: #短除法求二进制序列 num,yuShu=divmod(num,2) binaryNumList[i]=yuShu i-=1 print binaryNumList iplist=4*[0] for j in range(4): for i in range(8): iplist[j]+=binaryNumList[j*8+i]*pow(2,7-i) ipstr=str(iplist[0])+'.'+str(iplist[1])+'.'+str(iplist[2])+'.'+str(iplist[3]) return ipstrdef ip2int(ip): ipList=ip.split('.') binaryNumList=32*[0] intData=( int(ipList[0])<<24 )+( int(ipList[1])<<16 )+( int(ipList[2])<<8 )+int(ipList[3]) #注意这里一定要加括号,因为'+'的优先级高于'<<' return intData #109.151.53.1<->1838626049if __name__=='__main__': while True: print 20*'-' print '1:translate ip to int num;' print '2:translate int num to ip;' print '3:exit' print 20*'_' choice=raw_input("please enter the choice") if choice=='1': ip=raw_input('enter the ip') print ip2int(ip) elif choice=='2': num=int(raw_input('enter the num::')) print int2ip(num) else: break
12
# -*- coding: utf-8 -*-def findchr(string,chr): ''' 在字符串string中寻找第一次出现的chr的索引并返回,若没有返回-1 ''' i=0 for eachChr in string: if eachChr==chr: return i i+=1 return -1def rfindchr(string,chr): ''' 从string的右边开始查找第一次出现的chr的索引并返回,若没有则返回-1 ''' string=string[::-1] i=findchr(string,chr) if i==-1: return -1 return -i-1+len(string) #-1-i是其负数的索引,把其变成正数的索引故要加len(string)def substr(string,origchar,newchar): ''' 在字符串string中找到所有的origchr并全部替换成newchr,返回修改后的字符串 ''' string=list(string) #将其变换成列表是为了可以直接对list进行操作而不用每修改一次就要产生一次新的字符串对象,可以提高效率 i=0 for eachchr in string: if eachchr==origchar: string[i]=newchar i+=1 return ''.join(string)if __name__=='__main__': while True: print 20 * '_' print "1:find index of char in string" print "2:find index of char in string but start with right" print "3:replace origchar in string with newchar" print "4:exit" print 20 * '_' choice = raw_input("enter your choice::") if choice=='1': inStr=raw_input("enter the string and char(split with ',')::") string,chr=inStr.split(',') print findchr(string,chr) elif choice=='2': inStr = raw_input("enter the string and char(split with ',')::") string, chr = inStr.split(',') print rfindchr(string, chr) elif choice=='3': inStr = raw_input("enter the string ,origchar and newchar(split with ',')::") string, origchar, newchar = inStr.split(',') print substr(string,origchar,newchar) else: break
13
# -*- coding: utf-8 -*-def atoc(string): '''从右边开始查找实部与虚部分割的符号会比较方便,这样可以避免实部是负数 从而导致查找分割符号错误的情况''' string_len=len(string)-1 index=0 for i in range(string_len,0,-1): if ( string[i] in ('+','-') ) and string[i-1]!='e': #防止从右边开始第一个符号是e指数里面的 index=i real=float(string[0:index]) imag=float(string[index+1:-1]) return complex(real,imag)if __name__=='__main__': string=raw_input('enter the string\n') print atoc(string)
14
我的比较多的if
# -*- coding: utf-8 -*-import randomwhile True: print 20*'-' print '0:stone' print '1:cloth' print '2:scissor' print '3:exit' print 20*'-' user=int( raw_input('enter your choice::') ) winner='no body' choice=['stone','cloth','scissor'] if user!=3: computer=random.randrange(0,3) print "your\'s is:",choice[user] print "computer\'s is :",choice[computer] if (user,computer) in((0,2),(2,0)): if user>computer: winner="computer" else: winner='user' elif computer==user: winner="every body" elif computer>user: winner="computer" else : winner='user' print "winner is::",winner else: breakprint 'Rochambeau over'
博客【1】if比较少:
from random import choicedef Rochambeau(human_input,PC_input): if PRS_dict[human_input] == PRS_dict[PC_input]: return 'It is a tie.' elif PRS_dict[human_input] - PRS_dict[PC_input] == 1\ or PRS_dict[human_input] - PRS_dict[PC_input] == -2: return 'You win!' else: return 'PC win!'RPS_list = ['R','S','P'] PRS_dict = {'R':1,'S':0,'P':-1} if __name__ == "__main__": while True: human_input = (raw_input("Enter 'R' for 'Rock'\,'S' for 'Scissors' and 'P' for 'Paper'(q to quit):")).upper() if human_input == 'q': break else: PC_input = choice(RPS_list) print "PC's choice is %s." % PC_input print Rochambeau(human_input,PC_input)
19
# -*- coding: utf-8 -*-import randomdef out(list,geShi,num): length=len(list) (num_eachline,yuShu)=divmod(length,num) num_lastline=num_eachline+yuShu if geShi=='hang': for i in range(num-1): print list[0:num_eachline] del list[0:num_eachline] print list elif geShi=='lie': newList=list[0:num]#只是让newList和list类型一致,不是让newList取list的值 for i in range(num_eachline): for j in range(num): newList[j]=list[j*num_eachline+i] print newList print [-1,-1, list[-1] ]if __name__=='__main__': list=[random.randint(1,10) for i in range(100)] out(list ,'lie',3) out(list,'hang',3)
贴个结果:
-1代表空格
[2, 8, 10][10, 7, 2][6, 7, 1][7, 1, 2][5, 4, 5][9, 9, 5][9, 7, 8][7, 9, 5][1, 9, 2][10, 1, 5][9, 2, 9][7, 10, 3][2, 1, 3][1, 7, 5][4, 10, 3][10, 5, 9][2, 8, 9][8, 8, 7][10, 8, 7][3, 5, 8][4, 8, 1][3, 1, 3][4, 9, 9][4, 7, 1][9, 2, 4][4, 7, 9][3, 4, 2][3, 8, 4][9, 7, 4][7, 2, 9][3, 10, 2][3, 10, 6][10, 8, 2][-1, -1, 4][2, 10, 6, 7, 5, 9, 9, 7, 1, 10, 9, 7, 2, 1, 4, 10, 2, 8, 10, 3, 4, 3, 4, 4, 9, 4, 3, 3, 9, 7, 3, 3, 10][8, 7, 7, 1, 4, 9, 7, 9, 9, 1, 2, 10, 1, 7, 10, 5, 8, 8, 8, 5, 8, 1, 9, 7, 2, 7, 4, 8, 7, 2, 10, 10, 8][10, 2, 1, 2, 5, 5, 8, 5, 2, 5, 9, 3, 3, 5, 3, 9, 9, 7, 7, 8, 1, 3, 9, 1, 4, 9, 2, 4, 4, 9, 2, 6, 2, 4]
参考博客:
【1】https://my.oschina.net/linglingqixianke/blog/685275
0 0
- python核心编程第6章习题答案
- python核心编程-第7章课后习题答案
- python核心编程-第8章课后习题答案
- python核心编程v2.0 第8章习题答案
- Python核心编程v2.0 第10章习题答案
- Python核心编程v2.0 第11章习题答案
- Python核心编程v2.0 第12章习题答案
- python核心编程v2.0 第14章习题答案
- 《Python核心编程》第6章 习题
- 《Python核心编程》第6章 习题
- python核心编程-第六章习题答案
- python核心编程v2.0 第7章习题答案(下)
- python核心编程v2.0 第9章习题答案(上)
- Python核心编程v2.0 第9章习题答案(下)
- 《Python核心编程》第2章 习题
- 《Python核心编程》第3章 习题
- 《Python核心编程》第5章 习题
- 《Python核心编程》第7章 习题
- 人工智能:用爬山法、模拟退火算法实现八皇后和八数码问题
- Mahony 互补滤波
- linux
- 关联关系和依赖关系
- 以过来人的身份聊聊实习招聘、秋招、春招(给应届毕业生)
- python核心编程第6章习题答案
- 随手记:序列化要彻底
- CODEVS 1231最优布线问题
- 项目尾声(ListView+CheckBox进行批量删除)
- jsp bathpath
- URAL 1269
- 慕课网首页仿写—新闻中心
- 构造方法,初始化块和静态初始化块
- 初识Hadoop及其名词解释---Hadoop学习(1)