您的位置:首页 > 编程语言 > Python开发

Python 核心编程第六章练习

2015-04-02 15:29 477 查看
1-1:安装了Python

1-2:1、鼠标点击’run’。2、F5

1-3:在Python27/lib目录中

看了1/3的string.py,看到了三个引号加注释的好处,摘一段:

"""A collection of string operations (most are no longer used).

Warning: most of the code you see here isn't normally used nowadays.
Beginning with Python 1.6, many of these functions are implemented as
methods on the standard string object. They used to be implemented by
a built-in module called strop, but strop is now obsolete itself.

Public module variables:

whitespace -- a string containing all characters considered whitespace
lowercase -- a string containing all characters considered lowercase letters
uppercase -- a string containing all characters considered uppercase letters
letters -- a string containing all characters considered letters
digits -- a string containing all characters considered decimal digits
hexdigits -- a string containing all characters considered hexadecimal digits
octdigits -- a string containing all characters considered octal digits
punctuation -- a string containing all characters considered punctuation
printable -- a string containing all characters considered printable

"""


一味读书而不思考,就会因为不能深刻理解书本的意义而不能合理有效利用书本的知识,甚至会陷入迷茫。而如果一味空想而不去进行实实在在地学习和钻研,则终究是沙上建塔,一无所得。

2-1:熟悉print %等操作符

6-4:接收元组或者列表,是输出平均分和各科得分等级

a=(99,89,79,61,59,)
print  float(sum(a))/len(a)
d=[]
def c(x):
if x in range(90,101):
return 'A'
elif x in range(80,90):
return 'B'
elif x in range(70,80):
return 'C'
elif x in range(60,70):
return 'D'
else:
return 'F'

for i in a:
d.append(c(i))
print d


2-7:依次输出字符串的每个字符

'''for loop
s=raw_input('Enter a string: ')
def p(x):
for i in s:
print i
p(s)
'''
'''while loop
s=raw_input('Enter a string: ')
def p(x):
t=0
while t<len(x):
print x[t]
t=t+1
p(s)
'''


6-5:

(a)更新你在练习2-7 里面的方案,使之可以每次向前向后都显示一个字符串的一个字符.

s=raw_input('Enter a string: ')
def p(x):
t=0
l=len(x)
while t<l:
print x[t],
print x[l-t-1]
t=t+1
p(s)


6–5. 字符串

(b)通过扫描来判断两个字符串是否匹配(不能使用比较操作符或者cmp()内建函数)。附加题:在你的方案里加入大小写区分.

a=raw_input('s1:')
b=raw_input('s2:')

def comp(x,y):
if len(x)!=0 and len(y)!=0 and len(x) == len(y):
l=len(x)
t=0
while t<l:
if x[t]==y[t]:
print str(t)+' is good'
t=t+1
else:
print 'Not really'
break
else:
print 'Not the same lenth or empty string'
comp(a,b)


输出:

s1:a
s2:A
Not really
>>>
s1:abcdefg
s2:abcdefk
0 is good
1 is good
2 is good
3 is good
4 is good
5 is good
Not really
>>>


(c)判断一个字符串是否重现(后面跟前面的一致).附加题:在处理除了严格的回文之外,加入对例如控制符号和空格的支持。

a=raw_input('s1:')
def c(x):
z=len(x)
if z<2:
return false
i=0
while i < z/2:
if x[i]==x[z-i-1]:
i+=1
print str(i)+' is good'
else:
print 'Not really'
break
c(a)


输出:

s1:qweewq
1 is good
2 is good
3 is good
>>>
s1:qwertyuiopoiuytrewq
1 is good
2 is good
3 is good
4 is good
5 is good
6 is good
7 is good
8 is good
9 is good
>>>
s1:qwe rr ewq
1 is good
2 is good
3 is good
4 is good
5 is good
>>>
s1:+qweewq+
1 is good
2 is good
3 is good
4 is good
>>>


(d)接受一个字符,在其后面加一个反向的拷贝,构成一个回文字符串.

a=raw_input('s1:')
def c(x):
y=x
t=len(x)
for i in reversed(x):
y=y+i
return y
print c(a)


s1:abc
abccba
>>>
s1:qwertyuiop
qwertyuioppoiuytrewq
>>>
s1:ab+c e
ab+c ee c+ba


6–6. 字符串.创建一个string.strip()的替代函数:接受一个字符串,去掉它前面和后面的空格(如果使用string.*strip()函数那本练习就没有意义了)

a=raw_input('s1:')
def c(x):
print 'lenth1:'+str(len(x))
k=''
if len(x)>1:
for i in x:
if i!=' ':
k=k+i
print 'lenth2:'+str(len(k))
return k
else:
print 'Not good'
print c(a)

s1:     acde
lenth:13
lenth:4
acde
>>>
s1:   abc
lenth1:9
lenth2:3
abc
>>>
s1:
a
lenth1:0
Not good
None


6-7:加注释,改BUG

#!/usr/bin/env python

#UNIX启动行
import string

#导入string模块
while 1:

#循环条件,一直为真,一直循环直到break
num_str = raw_input('Enter a number: ')

#用户输入一个数字保存起来
try:
#异常检测
num_num = string.atoi(num_str)

#locale.atoi(string)
Converts a string to an integer.

break

#转换完毕,跳出
except ValueError:
print "invalid input... try again"

#报错
fac_list = range(1, num_num+1)
print "BEFORE:", `fac_list`

#
i = 0
t=fac_list
#创建变量i赋初值为0
while i < len(t):

#设定循环条件.只想到讲过要遍历副本,修改正主。这时用来将小于他且不能被他整除的所有数输出。
if num_num % t[i] == 0:
del fac_list[i]

#
i = i+1

#不知道还有什么bug。输入6、20、12、30不会死循环了。
print "AFTER:", `fac_list`


6-8:输入一个整数,返回相应的英文,限定0~1000

lists = ['zero','one','two','three','four','five','six','seven','nine']
new = ''
while True:
try:
iput = int(raw_input('Please input a int(0~1000): '))
#上面要转换为整型,因为要做 0-1000的判断
#while True:...try:...except:...固定
if iput <0 or iput >1000:
continue
except:
continue
break
iput = str(iput)
for j in iput:
new+=lists[int(j)]+'-'
print new[0:-1]


6-9:输入分钟,返回小时数和分钟

z=int(raw_input('min num:'))
y=[]
y=divmod(z,60)
#求商取余函数divmod.被除数,除数。返回商、余数列表
print str(y[0]) + ':'+ str(y[1])


5-13输入小时,返回分钟

def conversion(a,b):
return a*60+b
time=raw_input('time HH:MM format: ')
t=time.split(':')
print conversion(int(t[0]),int(t[1]))


输出:

time HH:MM format: 12:31
751
>>>
min num:751
12:31
>>>


6-10 写一个函数,返回一个跟输入字符串相似的字符串,要求字符串的大小写反转

例如: Mr.Ed 返回 mR.eD

def c(x):
return x.swapcase()
t=raw_input('A string: ')
print c(t)


>>>
A string: Mr.Ed
mR.eD


这个方法非常好:

import string
def Tran(strTemp):
lst = list(strTemp)
for i in range(len(lst)):
if lst[i] in string.lowercase:
lst[i] = lst[i].upper()
elif lst[i] in string.uppercase:
lst[i] = lst[i].lower()
return "".join(lst)
#这句list 变 string 的方法非常给力

if __name__ == "__main__":
while True:
name = raw_input("please enter the string(-1 to quit):")
if name == "-1":
break
print "the new strange string is:%s" % (Tran(name))


6–11.转换

(a)创建一个从整数到IP 地址的转换程序,如下格式: WWW.XXX.YYY.ZZZ.

(b)更新你的程序,使之可以逆转换.

def tranFromIPToInt(strIP):
lst = strIP.split(".")
if len(lst) != 4:
return "error ip"
return int(lst[0]) * (256 ** 3) + int(lst[1]) * (256 ** 2) +\
int(lst[2]) * 256 + int(lst[3])
def tranFromIntToIP(strInt):
ip1 = 0
ip2 = 0
ip3 = 0
ip4 = 0
ip1 = int(strInt) / (256 ** 3)
ip2 = (int(strInt) % (256 ** 3)) / (256 ** 2)
ip3 = (int(strInt) % (256 ** 2)) / 256
ip4 = int(strInt) % 256
return str(ip1) + "." + str(ip2) + "." + str(ip3) + "." + str(ip4)
c=raw_input( "input 'b' for IP-->INT or 'a' for INT-->IP :")
if c=='a':
x=raw_input('A int: ')
print tranFromIntToIP(x)
elif c=='b':
y=raw_input('A IP: ')
print tranFromIPToInt(y)


input 'b' for IP-->INT or 'a' for INT-->IP :b
A IP: 211.71.232.55
3544705079
>>>
input 'b' for IP-->INT or 'a' for INT-->IP :a
A int: 3544705079
211.71.232.55
input 'b' for IP-->INT or 'a' for INT-->IP :b
A IP: 172.20.97.118
2887016822
>>>
input 'b' for IP-->INT or 'a' for INT-->IP :a
A int: 2887016822
172.20.97.118
>>>


6–12.字符串

(a)创建一个名字为findchr()的函数,函数声明如下:

def findchr(string, char)

findchr()

要在字符串string 中查找字符char,找到就返回该值的索引,否则返回-1.不能用 string.*find()或者string.*index()函数和方法

def findchr(string,char):
t=0
p=[]
while t<len(string):
if string[t]==char:
p.append(t)
t+=1
if p==[]:
return -1
else:
return p


(b)创建另一个叫rfindchr()的函数,查找字符char 最后一次出现的位置.它跟findchr()工作

类似,不过它是从字符串的最后开始向前查找的.

def findchr(string,char):
t=0
p=[]
while t<len(string):
if string[t]==char:
p.append(t)
t+=1
if p==[]:
return -1
else:
return p[len(p)-1]
#改改输出就可以了。这时一种实现。


下面严格按照题目要求来:

def findchr(string,char):
t=0
p=[]
l=len(string)
while t<l:
if string[l-t-1]==char:
#从字符串最后开始查找
p.append(l-t-1)
t+=1
if p==[]:
return -1
else:
return p[0]


(c)创建第三个函数,名字叫subchr(),声明如下:

def subchr(string, origchar, newchar)

subchr()跟findchr()类似,不同的是,如果找到匹配的字符就用新的字符替换原先字符.返回 修改后的字符串.

def subchr(string,char,sub):
t=0
p=list(string)
l=len(p)
while t<l:
if p[t]==char:
p[t]= sub
t+=1
return "".join(p)
#join方法非常给力。让list转换为string.


6-13 autc的实现,复数什么的不明白。

6–14.随机数.设计一个”石头,剪子,布”游戏,有时又叫”Rochambeau”,你小时候可能玩过,下面

是规则.你和你的对手,在同一时间做出特定的手势,必须是下面一种手势:石头,剪子,布.胜利者从

下面的规则中产生,这个规则本身是个悖论.

(a) 布包石头.

(b)石头砸剪子,

(c)剪子剪破布.在你的计算机版本中,用户输入她/他的选项,计算机找一个随机选项,然后由你

的程序来决定一个胜利者或者平手.注意:最好的算法是尽量少的使用if 语句.

简单实现:

a=raw_input('s,j,b.try:')
import random
i=random.randint(0,2)
dic={0:'s',1:'j',2:'b'}
b=dic[i]
print a+' vs '+b
if a=='s':
if b=='s':
print 0
elif b=='j':
print 1
elif b=='b':
print -1
elif a=='j':
if b=='s':
print -1
elif b=='j':
print 0
elif b=='b':
print 1
elif a=='b':
if b=='s':
print 1
elif b=='j':
print -1
elif b=='b':
print 0


严格实现,少用if

import random
def Rochambeau(string):
dict1 = {"stone":"1","shears":"2","cloth":"3"}
dictAll = {"12":"lose","23":"lose","31":"lose","11":"equal","22":"equal","33":"equal","21":"win","32":"win","13":"win"}
randomNum = random.randrange(1,4)
return "you are:%s" % dictAll[dict1[string] + str(randomNum)]

if __name__ == "__main__":
while True:
string = raw_input("please enter stone,shears or cloth(q to quit):")
if string.lower() == "q":
break
if (string != "stone") and (string != "shears") and (string != "cloth"):
print "error input."
continue
print Rochambeau(string)


6–15.转换

(a)给出两个可识别格式的日期,比如 MM/DD/YY或者DD/MM/YY 格式,计算出两个日期间的天数.

(b)给出一个人的生日,计算从此人出生到现在的天数,包括所有的闰月.

(c)还是上面的例子,计算出到此人下次过生日还有多少天.

百度知道的一个回答:日期格式是 YYYY-MM-DD

def datedif(date1,date2):

if date1==date2:
return 0
from datetime import date
d1=map(int,date1.split('-'))
d2=map(int,date2.split('-'))
d1=date(d1[0],d1[1],d1[2])
d2=date(d2[0],d2[1],d2[2])
return (d1-d2).days
def dttoday(date1):

from datetime import date
date2= date.today().isoformat()
return datedif(date1,date2)
def dtb(date1):

from datetime import date
today=date.today()
d1=map(int,date1.split('-'))
d1=date(today.year,d1[1],d1[2])
if today>d1:
d1=d1.replace(year=d1.year+1)
return (d1-today).days


利用的是time 和datetime模块的函数

找不到教程,英文学起来吃力,而且学了不用等于没有学。

所以就探索了一下。

>>> d1=[2,4,6]
>>> from datetime import date
>>> d1=date(d1[0],d1[1],d1[2])
>>> d1
datetime.date(2, 4, 6)
#date()函数将列表转换成datetime.date()格式。
>>> d2=[4,6,8]
>>> d2=date(d2[0],d2[1],d2[2])
>>> print (d1-d2).days
-794
#利用上面的(d1-d2).days很轻易就算出了天数


6–16.矩阵.处理矩阵M 和N 的加和乘操作

不会。

6–17.方法.实现一个叫myPop()的函数,功能类似于列表的pop()方法,用一个列表作为输入,移除列表的最新一个元素,并返回它.

def myPop(q):
print 'Original:'+str(q)
del q[len(q)-1]
print 'After del:'+str(q)
myPop([1,2,3,4])


习题6.18:

zip返回列表。列表元素由元组类型组成。

>>> fn = ['ian','stuart','david']
>>> ln = ['bairnson','elliott','paton']
>>> for i,j in zip(fn, ln):
print ('%s %s' %(i,j)).title()
Ian Bairnson
Stuart Elliott
David Paton
>>> type(zip(fn,ln))
<type 'list'>
>>> x=[1,2,3]
>>> y=[4,5,6]
>>> for i,j in zip(x, y):
print ('%s %s' %(i,j)).title()
1 4
2 5
3 6


文档:zip([iterable, …]) This function returns a list of tuples。

6–19.多列输出.有任意项的序列或者其他容器,把它们等距离分列显示.由调用者提供数据和输出格式.例如,如果你传入100 个项并定义3 列输出,按照需要的模式显示这些数据.这种情况下,应该是两列显示33 个项,最后一列显示34 个.你可以让用户来选择水平排序或者垂直排序.

/article/3488649.html

最后矩阵反转不太明白,哎,先记录一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐