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--笔记
书写可维护的代码 1,最小全局变量 在js中不用声明变量就可以直接使用,因此注意不要没有声明就使用.(无意中创建的全局变量)比如使用任务链进行var声明.var a=b=12;正确写法为var ...
- 数论 UVALive 2911
这道题是一道数论题. 题目的意思是告诉m.p.a.b,并且告诉你xi满足的两个条件.让你求出 xp1 + xp2 +...+ xpm 的最大值(其中p<=12,切p是偶数). 这里需要对于xi所 ...
- Angular2 CLI 快速开发
Angular2 CLI 快速开发 http://www.tuicool.com/articles/z6V3Ubz 解决npm 的 shasum check failed for错误(npm注册国内镜 ...
- js-PC版监听键盘大小写事件
//获取键盘按键事件,可以使用keyup. //问题:获取到键盘的按下Caps lock键时,不能知道当前状态是大写.还是小写状态. //解决: 设置一个全局判断大小写状态的 标志:isCapital ...
- iOS应用之间调用
//// iOS应用之间调用.h// IOS笔记 1.判断系统里是否安装了某个app.比如新浪微博应用注册了URL scheme为@"weibo",我们可以通过[[UIAppl ...
- 《当心PyCharm里的中文引号陷阱》
用PyCharm照着书敲的一段Python代码,运行起来总报错: "UnicodeEncodeError: 'ascii' codec can't encode character '\u2 ...
- ListView的属性及方法详解
本文转载于:http://blog.csdn.net/vector_yi/article/details/23195411 近期在重新学习Android控件知识,目前进行到ListView,感觉这是一 ...
- gui2
事件:描述发生了什么的对象. 存在各种不同类型的事件类用来描述各种类型的用户交互. 事件源:事件的产生器. 事件处理器:接收事件.解释事件并处理用户交互的方法. 比如在Button组件上点击鼠标会产生 ...
- 在Angular1.X中使用CSS Modules
在Angular1.5中,增加了一个Component方法,并且定义了组件的若干生命周期hook,在代码规范中也是推崇组件化开发,但是很遗憾的是,CSS模块化组件化的问题并没有得到解决,大部分项目的打 ...
- WCF部署于IIS使用的几个问题总结
Q:wcf 远程服务器返回错误: (405) 不允许的方法. A: new SqlServerOperateClient("BasicHttpBinding_ISqlServerOperat ...