1、python装饰器
刚刚接触python的装饰器,简直懵逼了,直接不懂什么意思啊有木有,自己都忘了走了多少遍Debug,查了多少遍资料,猜有点点开始明白了。总结了一下解释得比较好的,通俗易懂的来说明一下:
小P闲来无事,随便翻看自己以前写的一些函数,忽然对一个最最最基础的函数起了兴趣:
def sum1():
sum = 1 + 2
print(sum)
sum1()
此时小P想看看这个函数执行用了多长时间,所以写了几句代码插进去了:
import time def sum1():
start = time.clock()
sum = 1+2
print(sum)
end = time.clock()
print("time used:",end - start) sum1()
运行之后,完美~~
可是随着继续翻看,小P对越来越多的函数感兴趣了,都想看下他们的运行时间如何,难道要一个一个的去改函数吗?当然不是!我们可以考虑重新定义一个函数timeit,将sum1的引用传递给他,然后在timeit中调用sum1并进行计时,这样,我们就达到了不改动sum1定义的目的,而且,不论小P看了多少个函数,我们都不用去修改函数定义了!
import time def sum1():
sum = 1+ 2
print (sum) def timeit(func):
start = time.clock()
func()
end =time.clock()
print("time used:", end - start) timeit(sum1)
咂一看,没啥问题,可以运行!但是还是修改了一部分代码,把sum1() 改成了timeit(sum1)。这样的话,如果sum1在N处都被调用了,你就不得不去修改这N处的代码。所以,我们就需要杨sum1()具有和timeit(sum1)一样的效果,于是将timeit赋值给sum1。可是timeit是有参数的,所以需要找个方法去统一参数,将timeit(sum1)的返回值(计算运行时间的函数)赋值给sum1。
import time def sum1():
sum = 1+ 2
print (sum) def timeit(func):
def test():
start = time.clock()
func()
end =time.clock()
print("time used:", end - start)
return test sum1 = timeit(sum1)
sum1()
这样一个简易的装饰器就做好了,我们只需要在定义sum1以后调用sum1之前,加上sum1= timeit(sum1),就可以达到计时的目的,这也就是装饰器的概念,看起来像是sum1被timeit装饰了!Python于是提供了一个语法糖来降低字符输入量。
import time def timeit(func):
def test():
start = time.clock()
func()
end =time.clock()
print("time used:", end - start)
return test @timeit
def sum1():
sum = 1+ 2
print (sum) sum1()
重点关注第11行的@timeit,在定义上加上这一行与另外写sum1 = timeit(sum1)完全等价。
2、递归算法
def divide(n,val):
n += 1
print(val)
if val / 2 > 1:
aa = divide(n,val/2)
print('the num is %d,aa is %f' % (n,aa))
print('the num is %d,val is %f' % (n,val))
return(val) divide(0,50.0) 结果说明(不return时相当于嵌套循环,一层层进入在一层层退出):
50.0
25.0
12.5
6.25
3.125
1.5625
the num is 6,val is 1.562500
the num is 5,aa is 1.562500
the num is 5,val is 3.125000
the num is 4,aa is 3.125000
the num is 4,val is 6.250000
the num is 3,aa is 6.250000
the num is 3,val is 12.500000
the num is 2,aa is 12.500000
the num is 2,val is 25.000000
the num is 1,aa is 25.000000
the num is 1,val is 50.000000 2、递归时return:
def divide(n,val):
n += 1
print(val)
if val / 2 > 1:
aa = divide(n,val/2)
print('the num is %d,aa is %f' % (n,aa))
return(aa)
print('the num is %d,val is %f' % (n,val))
return(val) divide(0,50.0) 结果说明(return时就直接结束本次操作):
50.0
25.0
12.5
6.25
3.125
1.5625
the num is 6,val is 1.562500
the num is 5,aa is 1.562500
the num is 4,aa is 1.562500
the num is 3,aa is 1.562500
the num is 2,aa is 1.562500
the num is 1,aa is 1.562500
用递归实现斐波那契函数
def feibo(first,second,stop,list): if first >= stop or second >= stop:
return list
else:
sum = first + second
list.append(sum)
if sum <= stop:
return feibo(second,sum,stop,list) return list if __name__ == '__main__':
first = int(raw_input('please input the first number:'))
second = int(raw_input('please input the second number:'))
stop = int(raw_input('please input the stop number:'))
l = [first,second]
a = feibo(first,second,stop,l)
print(a)
3、简易计算器
该计算器思路:
1、递归寻找表达式中只含有 数字和运算符的表达式,并计算结果
2、由于整数计算会忽略小数,所有的数字都认为是浮点型操作,以此来保留小数