Python基础教程第2版 6:抽象
http://blog.chinaunix.net/uid-21142030-id-5676171.html
抽象与结构,事件流程
创建函数是组织程序的关键.def
使用函数改变数据结构(比如list,dict)是将程序抽象化的好方法.
函数定义中的参数是形参
函数调用中的参数是实参
函数通过参数获取值.
函数内部作用域修改参数值不会影响外部值.
抽象的要点是隐藏更新时的烦琐细节.
函数只能修改参数对象本身.
一个将姓名查询添加程序
-
#!/usr/bin/env python
-
#-*- coding:utf-8 -*-
-
'''
-
斐波那契数列:初始为0,1,列表中的一个数字是前两个元素的和
-
'''
-
num=int(raw_input('请输入要计算的斐波那契数列的数目:'))
-
def fibs(num):
-
'文档字符串 fibs.__doc__查看'
-
result=[0,1]
-
for i in range(num-2):
-
result.append(result[-2]+result[-1])
-
return result
-
print fibs(num)
-
#初始化数据库
-
def initdata(data):
-
data['first']={}
-
data['middle']={}
-
data['last']={}
-
storage={}
-
initdata(storage)
-
me='eric lei wang'
-
you='talen tf HAO'
-
her='mei liu'
-
#查询方法
-
def lookup(database,lable,name):
-
result=database[lable].get(name)
-
return result
-
#录入数据库
-
def store(database,username):#把用户存入数据库中
-
#1.分割用户名
-
names=username.split()
-
lables=['first','middle','last']
-
if len(names)==2:
-
names.insert(1,'')
-
for lable,name in zip(lables,names):
-
#判断是否已经存在
-
people=lookup(database,lable,name)
-
if people:
-
#如果列表中有值,直接添加
-
people.append(username)
-
else:
-
#如果列表没有值,新创建,注意,这里生成的是列表.
-
database[lable][name]=[username]
-
store(storage,me)
-
store(storage,me)
-
store(storage,you)
-
store(storage,her)
-
print storage
关键字参数和默认值
位置参数与关键字参数是可以联合使用的.除非完全清楚程序的功能和参数的意义,否则应该避免混合使用.
使用*收集任意多的参数,返回数组.
使用**收集任意多的关键字参数,返回字典.
修改一下上面的程序,支持多个名字同时录入
-
#!/usr/bin/env python
-
#-*- coding:utf-8 -*-
-
'''
-
斐波那契数列:初始为0,1,列表中的一个数字是前两个元素的和
-
'''
-
num=int(raw_input('请输入要计算的斐波那契数列的数目:'))
-
def fibs(num):
-
'文档字符串 fibs.__doc__查看'
-
result=[0,1]
-
for i in range(num-2):
-
result.append(result[-2]+result[-1])
-
return result
-
print fibs(num)
-
#初始化数据库
-
def initdata(data):
-
data['first']={}
-
data['middle']={}
-
data['last']={}
-
storage={}
-
initdata(storage)
-
me='eric lei wang'
-
you='talen tf HAO'
-
her='mei liu'
-
#查询方法
-
def lookup(database,lable,name):
-
result=database[lable].get(name)
-
return result
-
#录入数据库
-
def store(database,*usernames):#把用户存入数据库中
-
#1.分割用户名
-
for username in usernames:
-
names=username.split()
-
lables=['first','middle','last']
-
if len(names)==2:
-
names.insert(1,'')
-
for lable,name in zip(lables,names):
-
#判断是否已经存在
-
people=lookup(database,lable,name)
-
if people:
-
#如果列表中有值,直接添加
-
people.append(username)
-
else:
-
#如果列表没有值,新创建,注意,这里生成的是列表.
-
database[lable][name]=[username]
-
store(storage,me,you)
-
store(storage,me)
-
store(storage,you)
-
store(storage,her)
-
print storage
-
请输入要计算的斐波那契数列的数目:11
-
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
-
{'middle': {'tf': ['talen tf HAO', 'talen tf HAO'], 'lei': ['eric lei wang', 'eric lei wang'], '': ['mei liu']}, 'last': {'liu': ['mei liu'], 'wang': ['eric lei wang', 'eric lei wang'], 'HAO': ['talen tf HAO', 'talen tf HAO']}, 'first': {'mei': ['mei liu'], 'eric': ['eric lei wang', 'eric lei wang'], 'talen': ['talen tf HAO', 'talen tf HAO']}}
-
参数练习
-
def story(**kwds):
-
return 'Once upon a time,there was a %(job)s called %(name)s.' % kwds
-
def power(x,y,*others):
-
if others:
-
print 'Received redundant parameters:',others
-
return pow(x,y)
-
def interval(start, stop=None,step=1):
-
'打印指定范围的数字'
-
if stop is None:
-
start,stop=0,start
-
result=[]
-
while start < stop:
-
result.append(start)
-
start+=step
-
return result
-
print story(job='ttserver',name='workhard')
-
print story(name='mile',job='assssfsffa')
-
params={'job':'job1','name':'nameserver'}
-
print story(**params)
-
print power(2,3)
-
print power(y=4,x=5)
-
params=(5,)*2
-
print power(*params)
-
print power(3,3,'talen')
-
print interval(10)
-
print interval(1,5)
-
print interval(3,12,4)
-
print power(*interval(3,7))
-
Once upon a time,there was a ttserver called workhard.
-
Once upon a time,there was a assssfsffa called mile.
-
Once upon a time,there was a job1 called nameserver.
-
8
-
625
-
3125
-
Received redundant parameters: ('talen',)
-
27
-
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-
[1, 2, 3, 4]
-
[3, 7, 11]
-
Received redundant parameters: (5, 6)
-
81
-
嵌套函数返回内嵌套在内的函数是带着返回的函数的环境和相关局部变量一起返回的,所以可以调用外部函数时附加变量值给返回的函数.
def A(a):
def B(b):
a+b
return B
A(a)(b)或
C=A(a)
C(b)
C是A的返回函数即C=B
递归
函数调用自身的行为就是递归
递归必须以最小可能性为结束
-
#!/usr/bin/env python
-
#-*- coding:utf-8 -*-
-
def factorial(n):
-
result=n
-
for i in range(1,n):
-
result*=i
-
print result
-
return result
-
print('最终结果是%s' %factorial(5))
-
-
def factorial2(n):
-
if n == 1 :
-
return 1
-
else:
-
return n*factorial2(n-1)
-
print('阶乘的结果是%s' % factorial2(6))
-
-
def power(x,n):
-
result=x
-
if n == 0:
-
return 1
-
else:
-
return result * power(x,n-1)
-
print(power(3,3))
-
5
-
10
-
30
-
120
-
最终结果是120
-
阶乘的结果是720
-
27
二元查找
如果不自己写,标准库有bisect模块可以有效实现二元查找.
宇宙中的粒子数约为10的87次方,只要290个问题就能分辨它们.
-
#二元运算
-
-
#元素:序列,数,位置,范围最小值位置,最大值位置
-
def search(sequence,number,lower=0,upper=None):
-
#先判断是否在序列中
-
if number in sequence:
-
if upper is None:
-
upper=len(sequence)-1
-
if lower==upper:
-
return upper
-
else:
-
#定义中间数,不能
-
middle=(lower+upper)//2
-
#判断在哪一边
-
if number > sequence[middle]:
-
return search(sequence,number,middle+1,upper)
-
else:
-
return search(sequence,number,lower,middle)
-
else:
-
return '没有这个数字'
-
seq=[34,67,8,123,4,100,95]
-
seq.sort()
-
print seq
-
print('数字位于%s' % search(seq,34))
-
print('数字位于%s' % search(seq,55))
-
print('数字位于%s' % search(seq,95))
-
[4, 8, 34, 67, 95, 100, 123]
-
数字位于2
-
数字位于没有这个数字
-
数字位于4
阅读(1193) | 评论(0) | 转发(0) |