递归函数
#递归求和
def mysum(L):
print(L)
if not L:
return 0
else:
return L[0] + mysum(L[1:])
print(mysum([1,2,3,4,5]))
"""
[1, 2, 3, 4, 5]
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]
15
"""
#递归求和
def mysum(L):
print(L)
return 0 if not L else L[0]+mysum(L[1:])
# return L[0] if len(L)==1 else L[0]+mysum(L[1:])
# first,*rest = L
# return L[0] if not rest else first +mysum(rest)
try:
# L=[1,2,3,4,5]
L=[]
mysum(L)
except TypeError:
print("wrong")
# print(mysum([1,2,3,4,5]))
# print(mysum(('s','p','a','m')))
# print(mysum(['spam','ham','eggs']))
#处理任意结构
def sumtree(L):
tot = 0
for x in L:
if not isinstance(x,list):
tot += x
else:
tot += sumtree(x)
return tot
L = [1,[2,[3,4],[4,[5,6]]]]
print(sumtree(L))
函数对象:属性和注解
函数对象可以赋值给其他的名字、传递给其他函数、嵌入到数据结构、从一个函数返回给另一个函数。
def echo(message):
print(message)
print(echo('Direct call'))
x = echo
print(x('Indirect call'))
def indirect(func,arg):
func(arg)
print(indirect(echo,'Argument call!'))
def make(label):
def echo(message):
print(label + ':'+message)
return echo
F = make('Spam')
F('Ham!')
F('Eggs!')
匿名函数:lambda
在序列中映射函数:map
counters = [1,2,3,4]
updated = []
for x in counters:
updated.append(x+10)
print(updated)
counters = [1,2,3,4]
def inc(x):return x+10
print(list(map(inc,counters)))
print(list(map((lambda x:x+3),counters)))
"""results:
[11,12,13,14]
[11,12,13,14]
[4, 5, 6, 7]
"""
函数式编程工具:filter和reduce
import numpy
print(list(range(-5,5)))
print(list(filter((lambda x:x>0),range(-5,5))))
print(list(map(lambda x:x>0,range(-5,5))))
res = []
for x in range(-5,5):
if x > 0:
res.append(x)
print(res)
from functools import reduce
print(reduce((lambda x,y:x+y),[1,2,3,4]))
print(reduce((lambda x,y:x*y),[1,2,3,4]))
"""
结果如下:
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
[1, 2, 3, 4]
[False, False, False, False, False, False, True, True, True, True]
[1, 2, 3, 4]
10
24
"""
from functools import reduce
print(reduce((lambda x,y:x+y),[1,2,3,4]))
print(reduce((lambda x,y:x*y),[1,2,3,4]))
def myreduce(function,sequence):
tally = sequence[0]
for next in sequence[1:]:
tally = function(tally,next)
return tally
print(myreduce((lambda x,y:x+y),[1,2,3,4,5]))
print(myreduce((lambda x,y:x*y),[1,2,3,4,5]))
"""
结果如下:
10
24
15
120
"""