遞歸
- 特性
- 必須有明確的結束條件;
- 每進入深一層遞歸,問題規模比上層應有所減小;
- 遞歸效率不高,層次更多會致使棧溢出;
def calc(n):
print(n)
if n // 2 > 0:
return calc(n // 2)
calc(10)
![](http://static.javashuo.com/static/loading.gif)
函數式編程
- 計算機:在計算機層面,CPU執行的是加減乘除以及各類判斷和跳轉指令代碼,於是彙編是最貼近計算機的語言,越接近計算機底層的語言執行效率越高;
- 計算:指數學意義上的計算,越抽象的計算,離計算機硬件越遠,效率越低;
- 定義:一種抽象程度極高的編程範式,純粹的函數式編程語言編寫的函數沒有變量,故對於一個函數,只要輸入肯定,輸出就肯定,函數式編程是一種討論如何編程的方法論,主要思想是把運算過程儘可能集成一系列嵌套的函數調用;
高階函數
def add(x, y, func):
return func(x) * func(y)
result = add(4, 8, abs)
print(result)
![](http://static.javashuo.com/static/loading.gif)
修飾器
- 原則:
- 不能修改被裝修函數的源代碼;
- 不能修改被裝飾函數的調用方式;
# --*--coding:utf-8--*--
#! /usr/bin/python3
user, passwd = 'k', '12345'
def auth(func):
def wrapper(*args, **kwargs):
username = input('username:').strip()
password = input('passwd:').strip()
if user == username and passwd == password:
print('passed')
func(*args, **kwargs)
else:
exit('Invalid username or password.')
return wrapper
def index():
print('welcomt to index page')
@auth
def home():
print('welcome to home page')
@auth
def bbs():
print('welcomt to bbs page')
index()
home()
bbs()
![](http://static.javashuo.com/static/loading.gif)
迭代器與生成器
- 生成器:
generator
,列表元素按某種算法推算而出,一邊循環一邊計算的機制,稱爲生成器,只有在調用時才產生相應數據;
- 直接做用域
for
循環的對象稱爲可迭代對象,Iterable
,使用isinstance()
判斷一個對象是否爲Iterable
對象,可用於for
循環的數據類型有 如下兩類:
- 集合數據類型:
list
、tuple
、dict
、set
、str
等
generator
,包括生成器和帶yield
的可迭代對象;
- 迭代器: 能夠別
next()
函數調用並不斷返回下一個值的對象稱爲迭代器,他們表示一個惰性計算的序列,Iterator
;
- 生成對象都是迭代器對象,
list
、dict
、str
雖然是可迭代對象,但卻不是迭代器,使用iter()
函數可將他們從迭代對象轉換爲迭代器;
json和pickle數據序列化
# json序列化與反序列化
import json
info = {
'name':'k',
'age':22
'sex':'男'
}
# 序列化
f = open('test.txt', 'w')
f.write(json.dumps(info))
# 反序列化
f = open('test.txt', 'r')
data = json.loads(f.read())
print(data['sex'])
f.close()
# pickle序列化與反序列化
import pickle
info = {
'name':'k',
'age':22
'sex':'男'
}
# 序列化
f = open('test.txt', 'wb')
f.write(pickle.dumps(info)) #與下一句做用相同
pickle.dump(info, f)
# 反序列化
f = open('test.txt', 'rb')
data = pickle.loads(f.read())
print(data['sex'])
f.close()