进入稍难的部分了
6.3创建函数
终于自己写函数了
#斐波那契数列
def fibs(num): #定义函数名和参数类型
result=[0,1] #初始化斐波那契的两项
for i in range(num-2):
result.append(result[-2]+result[-1])
return result #返回结果是斐波那契最后一项
print fibs(10) #结果[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#6.3.1文档化函数
def square(x):
"caculates the square of x"#函数说明
return x*x
print square(10)#结果100
print help(square)#查看函数说明
'''
Help on function square in module __main__:
square(x)
caculates the square of x
None
'''
#6.3.2并非真正函数的函数
def test():
print "a"
return
print "b"
x=test()
print test()
print x
'''
没看懂
结果
a
a
None
None
'''
6.4参数魔法
#6.4.2变参
#字符串(数字和元组)是不可变的
def change(n):
n[0]="c"
name=["a","b"]
change(name)
print name #结果['c', 'b']
#这个参数有点复杂,举个例子
def story(**kwds): #将**后面的参数转化为字典
return "once upon a time,there was a \
%(b)s called %(a)s."%kwds #连成一行
def power(x,y,*others): #将*后的所有参数转化为列表
if others:
print "receieved redundant parameters:",others
return pow(x,y)
def interval(start,stop=None,step=1):
"Imitates range() for step>0"
if stop is None: #如果没有为stop提供值
start,stop=0,start #指定参数
result=[]
i=start #计算start索引
while i<stop: #直到计算到stop的索引
result.append(i) #将索引添加到result内
i+=step #用step(>0)增加索引i
return result
#开始测试函数
print story(a="A",b="B") #结果 once upon a time,there was a B called A.
x={"a":"c","b":"d"}
print story(**x) #结果 once upon a time,there was a d called c.
del x["a"] #修改参数
print story(a="e",**x) #结果once upon a time,there was a d called e.
print power(2,3) #结果 8
print power(x=2,y=3) #结果 8
x=(5,)*2 #序列乘2
print power(*x) #结果 3125
print power(2,3,"hello world")
'''
结果
receieved redundant parameters: ('hello world',)
8
'''
print interval(5) #结果 [0, 1, 2, 3, 4]
print interval(1,5) #结果[1, 2, 3, 4]
print interval(3,12,4) #结果[3, 7, 11]
print power(*interval(3,7))
'''
结果
receieved redundant parameters: (5, 6)
81
'''
6.5作用域
6.6递归
#6.6.1阶乘和幂
#阶乘
#1.循环方法
def factorial(n):
result=n
for i in range(1,n):
result*=i
return result
print factorial(4) #结果 24
#2.迭代方法
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
print factorial(4) #结果 24
#幂
#1.循环方法
def power(x,y):
result=1
for i in range(y):
result*=x
return result
print power(2,3) #结果 8
#2.迭代方法
def power(x,y):
if y==0:
return 1
else:
return x*power(x,y-1)
print power(2,3) #结果 8
#6.2.2二分查找法
def search(sequence,number,lower=0,upper=None):
if upper is None:
upper=len(sequence)-1
if lower==upper:
assert number==sequence[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)
seq=[12,141,123,14,12,2,86,45,2,123]
seq.sort()
print seq #结果[2, 2, 12, 12, 14, 45, 86, 123, 123, 141]
print search(seq,14) #结果 4