8.5高階函數、遞歸函數和內置函數
阿新 • • 發佈:2018-03-05
內置函數 遞歸函數 高階函數 Python 高階函數、遞歸函數和內置函數
高階函數和遞歸函數
#函數名可以進行賦值,可以作為函數參數,可以作為返回值 #高階函數:允許導入函數作為參數導入或者返回值為函數 def f(n): return n*n def fun(a,b,fun1): an1=fun1(a)+fun1(b) return (an1) print(fun(1,2,f)) def sqrt(n): return n*n def function(a,b,function1): answer=function1(a)+function1(b) return answer print(function(1,8,sqrt)) # 65
#遞歸函數
#遞歸函數特點:自己調用自己,結束判斷
#遞歸可以寫的程序,循環都可以做,遞歸效率在很多時候很低
def recursion(n):
if n==1:
return 1
return n*recursion(n-1)
print(recursion(5))
# 120
#斐波那切數列 def fibo_seq(n): if n==1: return 0 elif n==2: return 1 else: return fibo_seq(n-1)+fibo_seq(n-2) print(fibo_seq(10))
內置函數(python3.0以後)
很多,網上也有很多,可以去看看。
print(any([1]))
print(eval("1+2*3")) #eval有計算器功能
#eval()函數能把字符串類型成其他類型執行,比如轉換成列表,元組和字典
#filter函數 list1=[1,2,3,4] def fun1(l): if l!=1: return l ret=filter(fun1,list1) # ret變成叠代器 print(ret) # <filter object at 0x000000911CD9B978> print(list(ret)) # [2, 3, 4]
#map函數
def fun2(l):
return l+2
ret1=map(fun2,list1)
print(ret1)
# <map object at 0x000000E5A604B9E8>
print(list(ret1))
# [3, 4, 5, 6]
#reduce函數
# def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
# """
# reduce(function, sequence[, initial]) -> value
#
# Apply a function of two arguments cumulatively to the items of a sequence,
# from left to right, so as to reduce the sequence to a single value.
# For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
# ((((1+2)+3)+4)+5). If initial is present, it is placed before the items
# of the sequence in the calculation, and serves as a default when the
# sequence is empty.
# """
# pass
from functools import reduce
def add1(x,y):
return x+y
print(reduce(add1,range(1,10)))
# 45
a=5
b=6
c=lambda a,b:a+b #lambda函數沒有名字,表示一個表達式
print(c(1,2))
# 3
#階乘:函數式編程的方法,命令式編程比較直觀
from functools import reduce
print(reduce(lambda a,b:a*b,range(1,6)))
#120
大家對內容有任何問題,歡迎留言,定在第一時間解答,謝謝大家!
8.5高階函數、遞歸函數和內置函數