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__" 方法中至少一个的对象.什么是非 ...
随机推荐
- April Fools Day Contest 2014
April Fools Day Contest 2014 A.C.H三道题目 ============================================================= ...
- OSX下Python模块安装常见问题解决
he following error occurred while trying to add or remove files in theinstallation directory: [Errno ...
- 使用Githua管理代码
原创博客:转载请标明出处:http://www.cnblogs.com/zxouxuewei/ 1.安装配置git服务器 a.安装ssh,因为git是基于ssh协议的,所以必须先装ssh: ...
- Git 基础
取得项目的 Git 仓库 有两种取得 Git 项目仓库的方法.第一种是在现存的目录下,通过导入所有文件来创建新的 Git 仓库.第二种是从已有的 Git 仓库克隆出一个新的镜像仓库来. 在工作目录中初 ...
- JQ轮播
首先是html结构,一个简单的轮播,主要分为三大层:div>ul>li,li里面的img图片. 其次,css样式:div固定住宽高,overflow:hidden:ul的宽度建议是动态获取 ...
- symfony2取得web目录绝对路径、相对路径、网址的函数是什么
对于你的需求,Symfony2通过DIC提供了kernel服务,以及request(请求)的封装. 在controller里(在其他地方你可以自行注入kernel,这个服务是HttpKernel库里的 ...
- 【python】用setup安装自定义模块和包
python解释器查找module进行加载的时候,查找的目录是存放在sys.path变量中的,sys.path变量中包含文件的当前目录.如果你想使用一个存放在其他目录的脚本,或者是其他系统的脚本,你可 ...
- ASP.NET: 正在中止线程 错误原及解决方法
#[操作记录]:2010-02-23 9:25:12 System.Threading.ThreadAbortException: 正在中止线程. 症状 如果使用 Response.End.Resp ...
- android模拟器停在Waiting for HOME解决方案
直接打开Android SDK Manager然后再从Android SDK Manager里的tools打开Android AVD Manager,删除掉在Eclipse里创建的模拟器.并在新建一个 ...
- Android ORMapping库
自己用Java的注解实现了Android SQLite的ORM库,之前写过XML的,不过感觉不是很稳定,效率.鲁棒性各方面都不太好,今天花了一下午的时间,补全了所有的注解.注释,生成了javadoc, ...