python 核心编程课后练习(chapter 6)
6-1
#6-1 #help(string)
import string str = "helloworld"
substr = "h1e" if string.find(str, substr) != -1:
print"substr=%s is part of %s" % (substr, str)
else:
print"not substring"
6-2
#6-2
import string
import keyword alphas = string.letters + '_'
nums = string.digits print "welcome"
print "testees must be at least 2 chars long." ips = raw_input("identifier:") if len(ips)== 1:
if ips[0] not in alphas:
print"single letter invalid"
else:
if not keyword.iskeyword(ips):
print "valid"
else:
print "invalid is keyword"
#print "valid"
elif len(ips) > 1:
if ips[0] not in alphas:
print "first symbol invalid"
else:
for others in ips[1:]:
if others not in alphas + nums:
print "invalid remaining"
break
else:
if not keyword.iskeyword(ips):
print "valid"
else:
print "invalid, is keyword"
else:
print"string should be at least 2 chars"
6-3
#6-3 import string nums = string.digits str=raw_input("Enter the nums:")
#a
a = []
for e in str:
a.append(int(e))
a.sort(reverse = True)
print a
#b
b = sorted(str, reverse = True)
print b
6-4
#6-4 def average(a):
size = len(a)
sum = 0
for e in a:
sum += int(e)
return float(sum)/float(size) print """
(a)add new
(other)exit
"""
a = [] opt = raw_input("your opt:")
while opt == "a":
a.append(raw_input("Enter the score:"))
opt = raw_input("your opt:") print "the average of the scores:%f" % average(a)
6-5
#6-5(a) inputstring = raw_input("Enter the string:") sz = len(inputstring) if sz == 1:
print inputstring
else:
i = 0
while i<sz:
if (i-1)<0:
print inputstring[i], inputstring[i+1]
elif (i+1)>=sz:
print inputstring[i-1], inputstring[i]
else:
print inputstring[i-1], inputstring[i], inputstring[i+1] i = i+1
#6-5(b) def str_cmp_helper(str1, str2):
lens = len(str1)
i = 0
while i<lens:
if str1[i]>str2[i]:
return 1
elif str1[i]<str2[i]:
return -1
i = i+1
return 0 def str_cmp(str1, str2):
if len(str1)>len(str2):
return 1
elif len(str1)<len(str2):
return -1
else:
return str_cmp_helper(str1, str2) str1 = raw_input("enter the str1:")
str2 = raw_input("enter the str2:") result = str_cmp(str1, str2)
if result == 1:
print "str1:%s > str2:%s" % (str1, str2)
elif result == 0:
print "str1:%s is the same to str2:%s" % (str1, str2)
else:
print "str1:%s < str2:%s" % (str1, str2)
#6-5(c) def is_palin(str):
lens = len(str) if lens == 1:
return True
else:
i = 0
while i<lens/2:
if str[i] <> str[lens -1 - i]:
return False
else:
i= i+1
return True inputstring = raw_input("enter the string:") if is_palin(inputstring):
print "%s is palin"% inputstring
else:
print "%s is not palin"% inputstring
#6-5(d) def palin(str):
lens = len(str)
if lens%2 != 0:
i = lens -1 -1
else:
i = lens - 1 while i>=0:
str = str +str[i]
i= i-1 return str inputstring = raw_input("enter the string:") print"the palin of %s is: %s" % (inputstring, palin(inputstring))
6-6
#6-6 def trim_end_blacks(str):
lens = len(str)
i = lens -1
#trim the end blanks
while i >=0 and str[i] == ' ':
str = str[:i]
i = i- 1
#trim the start blanks
while str[0]==' ' and len(str)!=0:
str = str[1:]
print str inputstr = raw_input("enter the string:") print """after trim the blanks in start and end pos:
%s change to %s
"""%(inputstr, trim_end_blacks(inputstr))
6-8
#6-8 print """
(zero,one, two, three, four, five, six, seven, eight, nine,),
(ten,eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen,),
(twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety,)
(hundred, thousand, million, billion,...)
""" units = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
hundreds = ["hundred", "thousand", "million", "billion"] def num_to_eng(num):
#get thousand
need_and = False
eng_str = ""
if(num == 0):
eng_str = "Zero"
return eng_str
num = num%10000
if num/1000 != 0:
need_and = True
eng_str = eng_str + units[num/1000-1]+" thousand "
num = num%1000
if num/100 !=0:
need_and = True
eng_str = eng_str + units[num/100 - 1]+" hundred "
if(need_and):
eng_str = eng_str + "and " num = num%100
if(num>19):
eng_str = eng_str + tens[num/10 - 2]+" "
num = num%10
if(num != 0):
eng_str = eng_str + units[num-1]
elif(num>9):
eng_str = eng_str + teens[num -10]
else:
eng_str = eng_str+ units[num-1]
return eng_str
num = raw_input("enter the number:")
print num_to_eng(int(num))
6-9
#6-9 def min_to_hm(t):
h = t/60
h=h%24 m = t%60 return "%d:%d"%(h,m) t = raw_input("enter the mins:")
print "the time is:%s" % min_to_hm(int(t))
6-10
#6-10
import string
def ul_covert(str):
return string.swapcase(str) str = raw_input("enter the string:") print ul_covert(str)
6-11
#6-11
def n_to_ip(num):
str = "%d" % num
if len(str)!= 12:
print "invalid ip"
return ""
else:
return str[:3]+":"+str[3:6]+":"+str[6:9]+":"+str[9:12] def ip_to_n(str):
if len(str)!=15:
print "invalid ip str"
return 0
else:
return int(str[0:3]+str[4:7]+str[8:11]+str[12:15]) num = int(raw_input("enter the ip num:"))
print"after covert to ip string: %s" % n_to_ip(num)
print"after convert to ip num: %d" % ip_to_n(n_to_ip(num))
6-12
#6-12 def findchr(string, char):
if char == "":
return 0
lens = len(string)
if lens == 0:
return -1
i=0
while i<lens:
if string[i] == char:
return i
else:
i=i+1
return -1 def rfindchr(string, char):
lens = len(string)
if char == "":
return lens
if lens == 0:
return -1
i = lens -1
while i>=0:
if string[i] == char:
return i
else:
i=i-1 return -1 def subchr(string, origchar, newchar):
lens = len(string)
i = 0
while i<lens:
if string[i]==origchar:
string = string[0:i]+newchar+string[i+1:]
i= i+1
return string print findchr("","")
print findchr("", "a")
print findchr("abc","a")
print findchr("abc", "d") print rfindchr("","")
print rfindchr("", "a")
print rfindchr("abc","a")
print rfindchr("dabcd", "d") print subchr("test", "t", "a")
6-13
#6-13
#import string def atoc(str):
real = 0
img = 0 lens = len(str) i = lens -1
if str[i] == "j":
if str[i-1]==")":
j = i -2
while j>=0:
if str[j] != "(":
j= j-1
else:
break
img = float(str[j+1:i-1])
i = j-1
else:
j=i
while j>0:
if str[j]=="+" or str[j]=="-":
break
else:
j=j-1
img = float(str[j+1:i])
i=j
real = float(str[0:i])
return complex(real, img) str = raw_input("enter the complex:")
print atoc(str)
6-14
#6-14
import string
import random def Rockhambocu(pc_opt,y_opt):
"""
pc_opt, the option of pc
y_opt, your option
(r)rock
(s)scissor
(c)cloth
"""
str_opt = "rsc" rsc_rule =[[0,-1,1],[1,0,-1],[-1,1,0]] pc_i = string.find(str_opt, pc_opt)
y_i = string.find(str_opt, y_opt) return rsc_rule[pc_i][y_i] def RSC_result(r):
result = ["fail", "draw", "win"]
return result[r+1] print """
enter your option:
(r)rock
(s)scissor
(c)cloth
(other)default r
""" y_opt = raw_input() str_opt ="rsc"
pc_opt = str_opt[random.randint(0,2)]
print "PC option is %s" % pc_opt print "you %s"% RSC_result(Rockhambocu(pc_opt, y_opt))
6-15
#6-15 def is_leap(y):
if y/400 == 0:
return True
elif y/4 == 0 and y/100 != 0:
return True
return False def check_date_valid(y, m, d):
"""
-1, invalid date
1, valid date
"""
if y<1:
return -1
if m<1 or m>12:
return -1
month_days = [31,28, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30]
if is_leap(y):
month_days[1] = 29
if d<1 or d>month_days[m-1]:
return -1 return 1 def calcu_days(y, m, d):
sum = d
month_days = [31,28, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30]
year_days = 365 if is_leap(y):
month_days[1] = 29 i = 1
while i<m:
sum = sum + month_days[i-1]
i=i+1
i=1
while i<y:
if is_leap(i):
sum = sum + year_days + 1
else:
sum = sum + year_days
i = i +1
return sum def days_between_tdate(date1, date2):
y1 = int(date1[6:])
m1 = int(date1[3:5])
d1 = int(date1[:2]) if check_date_valid(y1, m1, d1) == -1:
return -1 y2 = int(date2[6:])
m2 = int(date2[3:5])
d2 = int(date2[:2]) if check_date_valid(y2, m2, d2) == -1:
return -1 return abs(calcu_days(y1, m1, d1) - calcu_days(y2, m2, d2)) def all_days_your_life(birthday):
date = raw_input("Enter the date of today:")
return days_between_tdate(birthday, date) def days_of_next_birthday(birthday):
date = raw_input("Enter the date of today:") y1 = int(date[6:])
m1 = int(date[3:5])
d1 = int(date[:2]) if check_date_valid(y1, m1, d1) == -1:
return -1 y2 = y1
m2 = int(birthday[3:5])
d2 = int(birthday[:2]) if check_date_valid(y2, m2, d2) == -1:
return -1 if calcu_days(y2,m2,d2)<calcu_days(y1,m1,d1):
y2 = y2 +1 return calcu_days(y2,m2,d2)-calcu_days(y1,m1,d1) date1 = raw_input("Enter the date1:")
date2 = raw_input("Enter the date2:") print "the days between these two date is: %d days"% days_between_tdate(date1, date2) birthday = raw_input("enter the date you have born:")
print "the days you have been in the world: %s days"% all_days_your_life(birthday) print "the next birthday till now: %d days"% days_of_next_birthday(birthday)
6-16
#6-16 def add_matrix(M, N):
r1 = len(M)
c1 = len(M[0]) r2 = len(N)
c2 = len(N[0]) r = [([0]*r1) for i in range(c1)] if r1==r2 and c1==c2:
i = 0
while i<r1:
j = 0
while j<c1:
r[i][j] = M[i][j] + N[i][j]
print M[i][j], N[i][j]
j = j+1
i = i+1
return r
else:
return -1 def mul_matrix(M, N):
r1 = len(M)
c1 = len(M[0]) r2 = len(N)
c2 = len(N[0]) if c1 != r2:
return -1
r = [([0]*c2) for i in range(r1)] for i in range(r1):
for j in range(c2):
for i1 in range(c1):
r[i][j] = r[i][j] + M[i][i1]*N[i1][j]
i1 = i1 + 1
j = j +1
i= i+1
return r M = [[1,1], [2,0]]
N = [[-1,2], [9,0]] print add_matrix(M, N)
N=[[0, 2, 3], [1, 1, 2]]
print mul_matrix(M, N)
6-17
#6-17 def myPop(a):
if len(a[0]) == 0:
return -1
ret = a[0][-1] #a[0] = a[0][0: len(a[0])-1]
del a[0][-1]
print a[0]
return ret a = [1,2,3] print myPop([a])
print a
python 核心编程课后练习(chapter 6)的更多相关文章
- python 核心编程课后练习(chapter 5)
5-2 #5-2 def mul(x, y): return x * y print mul(4,5) 5-3 #5-3 def value_score(num): if 90<=num< ...
- python 核心编程课后练习(chapter 3)
3-8 #3-8 "makeTextFile.py -- create text file" import os ls = os.linesep #get filename fna ...
- python 核心编程课后练习(chapter 2)
2-4 #2-4(a) print "enter a string" inputstring = raw_input() print"the string is: &qu ...
- Python核心编程课后习题-第六章
1. 字符串, string模块中是否有一种字符串方法或者函数可以帮我鉴定一下一个字符串是否是另一个大字符串的一部分? str1 = 'abcdefghijklmnopqrstuv' print st ...
- Python 核心编程 课后习题 第五章
2. 操作符. (a) 写一个函数, 计算并返回两个数的乘积. (b) 写一段代码调用这个函数, 并显示它的结果. def multi(a,b): return a * b result = mult ...
- Python核心编程 课后练习 第二章
2.4 使用raw_input()函数得到用户输入. (a) 创建一段脚本使用raw_input()函数从用户输入得到一个字符串, 然后显示这个用户杠杠输入的字符串. #coding = utf-8 ...
- python核心编程(第二版)习题
重新再看一遍python核心编程,把后面的习题都做一下.
- Python核心编程这本书的一些错误
<Python核心编程第二版>这本书比<Python基础教程第二版修订版>详细很多,丰富了很多细节,虽然它是一本经典的入门书,但我发现还是存在一些明显的错误.在面向对象编程这一 ...
- Python核心编程-描述符
python中,什么描述符.描述符就是实现了"__get__"."__set__"或"__delete__" 方法中至少一个的对象.什么是非 ...
随机推荐
- javascript中escape()、unescape()、encodeURI()、encodeURIComponent()、decodeURI()、decodeURIComponent()比较
这些URI方法encodeURI.encodeURIComponent().decodeURI().decodeURIComponent()代替了BOM的escape()和unescape()方法.U ...
- 数论 UVAlive 2889
这是一道考察回文数的题目,要求你输出第k个回文数.在做题的过程中,可以发现回文数的分布的规律:一位数:9个,二位数:9个,三位数:90个,四位数:90个,五位数:900个,六位数:900个……. #i ...
- SQL Server 中存储过程的练习
建库建表建约束 插入数据 --建库建表建约束和插入测试数据 use bankDB go --1.完成存款,取款业务--存款 create proc usp_takeMoney ),),)=null,@ ...
- [转]Linux命令的返回值
Linux命令的返回值 对于某些监测脚本和探测命令蛮有用的: 在 Linux 下,不管你是启动一个桌面程序也好,还是在控制台下运行命令,所有的程序在结束时,都会返回一个数字值,这个值叫做返回值,或者称 ...
- (转) 变分自编码器(Variational Autoencoder, VAE)通俗教程
变分自编码器(Variational Autoencoder, VAE)通俗教程 转载自: http://www.dengfanxin.cn/?p=334&sukey=72885186ae5c ...
- H5页面在QQ和微信上分享,为什么不能自定义设置图片和摘要?
[记录]title标签中的页面标题为抓取标题.body内第一个img标签内的图片为自动抓取缩略图,图片宽高要大于300,如果不希望显示出来,将标签宽高皆设置为0.摘要显示为来源链接,如需自定义需要通过 ...
- 采用sqlserver的缺省配置,在生产环境经常碰到系统响应慢(甚至hung的情况)
请重视并正确配置sqlserver实例及数据库的参数,一般化的配置推荐如下: 1.数据和日志文件的初始大小分别设置为10G和2G,均设置为按照固定200M大小增长,不限制最大值: 2.sever实例设 ...
- AutoVue打开ProE工程图中文乱码
解决办法: 在AutoVue安装目录/Bin/allusers.ini中增加 [Options]ProELang=Chinese_cn
- 支付宝接入文档中TRADE_SUCCESS和TRADE_FINISHED的本质区别
之前一直不知道这2种状态到底有什么不同.支付宝中担保交易和即时到账交易对其的描述为: TRADE_SUCCESS 交易成功(或支付成功) TRADE_FINISHED 交易完成 一头雾水... ...
- Verilog HDL那些事_建模篇笔记(实验七:数码管电路驱动)
1.同步动态扫描 多个数码管的显示采用的是同步动态扫描方法,同步动态扫描指的是:行信号和列信号同步扫描,是一种并行操作. 2.数码管驱动电路实现思路 如果要求数码管显示我们想要的数字,首先需 ...