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)的更多相关文章

  1. 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< ...

  2. python 核心编程课后练习(chapter 3)

    3-8 #3-8 "makeTextFile.py -- create text file" import os ls = os.linesep #get filename fna ...

  3. python 核心编程课后练习(chapter 2)

    2-4 #2-4(a) print "enter a string" inputstring = raw_input() print"the string is: &qu ...

  4. Python核心编程课后习题-第六章

    1. 字符串, string模块中是否有一种字符串方法或者函数可以帮我鉴定一下一个字符串是否是另一个大字符串的一部分? str1 = 'abcdefghijklmnopqrstuv' print st ...

  5. Python 核心编程 课后习题 第五章

    2. 操作符. (a) 写一个函数, 计算并返回两个数的乘积. (b) 写一段代码调用这个函数, 并显示它的结果. def multi(a,b): return a * b result = mult ...

  6. Python核心编程 课后练习 第二章

    2.4 使用raw_input()函数得到用户输入. (a) 创建一段脚本使用raw_input()函数从用户输入得到一个字符串, 然后显示这个用户杠杠输入的字符串. #coding = utf-8 ...

  7. python核心编程(第二版)习题

    重新再看一遍python核心编程,把后面的习题都做一下.

  8. Python核心编程这本书的一些错误

    <Python核心编程第二版>这本书比<Python基础教程第二版修订版>详细很多,丰富了很多细节,虽然它是一本经典的入门书,但我发现还是存在一些明显的错误.在面向对象编程这一 ...

  9. Python核心编程-描述符

    python中,什么描述符.描述符就是实现了"__get__"."__set__"或"__delete__" 方法中至少一个的对象.什么是非 ...

随机推荐

  1. App Transport Security has blocked a cleartext HTTP (http://)

    使用SDWebImage加载“http://”开头的图片报错,错误如下: App Transport Security has blocked a cleartext HTTP (http://) r ...

  2. kernel/vsprintf.c

    /* *  linux/kernel/vsprintf.c * *  Copyright (C) 1991, 1992  Linus Torvalds */ /* vsprintf.c -- Lars ...

  3. EditBox问题的实现以及Junit测试框架的简要说明

    一.这周的EditBox由一个框改为三个框,同时进行测试,下面给出程序及截图 1 import java.util.regex.Matcher; 2 import java.util.regex.Pa ...

  4. rabbitmq, windows/linux, c/c++/node.js/golang/dotnet

    官网:http://www.rabbitmq.com/ zeromq 相当于 message backbone,而rabbitmq相当于message broker.有的应用系统中,二者并存. (1) ...

  5. ABBYY PDF Transformer+怎么标志注释

    ABBYY PDF Transformer+是一款可创建.编辑.添加注释及将PDF文件转换为其他可编辑格式的通用工具,可用来在PDF页面的任何位置添加注释(关于如何通过ABBYY PDF Transf ...

  6. JAVA之Forward 和 Redirect的区别

    1.从地址栏显示来说forward是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器.浏览器根本不知道服务器发送的内容从哪里来的,所以它的地址 ...

  7. [2014.01.27]wfChart 统计图组件 5.6

    本组件支持多种样式图表,包括柱型图.横柱型图.曲线图.饼图.点图.区域图.     可选择的8大主题风格,且主题可再配置,在加快开发的同时又提供更好的图像效果.     组件图表提供两种输出接口,包括 ...

  8. [综]聚类Clustering

    Annie19921223的博客 [转载]用MATLAB做聚类分析 http://blog.sina.com.cn/s/blog_9f8cf10d0101f60p.html Free Mind 漫谈 ...

  9. hive与hbase整合过程

    实现目标 Hive可以实时查询Hbase中的数据. hive中的表插入数据会同步更新到hbase对应的表中. 可以将hbase中不同的表中的列通过 left 或 inner join 方式映射到hiv ...

  10. PHPCMS v9 超级安全防范教程!

    一.目录权限设置很重要:可以有效防范黑客上传木马文件.如果通过 chmod 644 * -R 的话,php文件就没有权限访问了.如果通过chmod 755 * -R 的话,php文件的权限就高了. 所 ...