高阶函数
函数
定义函数
def fun(a, b):
return a + b
fun(1,2) # 调用函数
高阶函数:
- 实参是一个函数名;
- 函数的返回值是一个函数;
函数本身也可以赋值给变量,即:变量可以指向函数。
print(abs(-10))
f = abs
print(f(-10))
传递的参数包含函数名.
def fun(x,y, f):
return f(x), f(y)
print(fun(-10, 34, abs))
内置高阶函数:map reduce filter storted max min
map:======> [abs(i) for i in [-1, 3, -4, -5]]
对于序列每个元素求绝对值;
import random
from functools import reduce
print(list(map(abs, [-1, 3, -4, -5])))
对于序列每个元素求阶乘; 5!
def factoria(x):
"""对于x求阶乘"""
res = 1
for i in range(1, x + 1):
res = res * i
return res
li = [random.randint(2, 7) for i in range(10)]
print(list(map(factoria, li)))
reduce:
- PYTHON2中, 为内置函数;
PYTHON3中, 导入reduce, from functools import reduce
10!的阶乘 def multi(x, y): return x * y print(reduce(multi, range(1, 4)))
filter函数 ====> [i for i in range(1,11) if isodd(i)]
def idodd(x):
return x % 2 == 0
print(list(filter(idodd, range(1,11))))
拿出1~100之间所有的素数
def isPrime(num):
for i in range(2, num):
if num % i == 0:
return False
else:
return True
print(list(filter(isPrime, range(2,101))))
sorted
li.sort()和sorted()两种方法的区别?
1). 列表里面提供了sort方法, 其他数据结构没有.sorted方法可以对任何可迭代对象排序.
2).sort方法支持原地排序(变量排序后, 变量本身改变), sorted排序后返回一个新的列表,并不改变原变量的内容.
默认sort和sorted方法由小到大进行排序, reverse=True时, 由大到小进行排序.
li = [1,2,6,21324,67,2,23]
li.sort(reverse=True)
print(li)
print(sorted(li, reverse=True))
对于列表里面嵌套列表进行排序.
info = [
# 商品名称 商品数量 商品价格
('apple3', 200, 32),
('apple4', 40, 12),
('apple1', 40, 2),
('apple2', 1000, 23),
]
print(sorted(info))
def sorted_by_count(x): # x = ('apple3', 200, 32)
return x[1]
def sorted_by_price(x): # x = ('apple3', 200, 32)
return x[2]
# 先按照商品数量由小到大进行排序, 如果商品数量一致, 则按照商品价格由小到大进行排序.
def sorted_by_count_price(x): # x = ('apple3', 200, 32)
return x[1], x[2]
# 按照商品的数量进行排序, key代表排序的关键字
print(sorted(info, key=sorted_by_count))
# 按照商品的价格进行排序, key代表排序的关键字
print(sorted(info, key=sorted_by_price))
print(sorted(info, key=sorted_by_count_price))
对于字典里面嵌套字典进行排序
d = {
'003':{
'name':'apple1',
'count':100,
'price':10
},
'002': {
'name': 'apple1',
'count': 200,
'price': 2
},
}
print(d.items()) # [(id, {}), (), ()]
# x: ('003', {'name': 'apple1', 'count': 100, 'price': 10})
print(sorted(d.items(), key=lambda x: x[1]['count']))
print(sorted(d.items(), key=lambda x: x[1]['price']))
# x: {'name': 'apple1', 'count': 100, 'price': 10}
print(sorted(d.values(), key=lambda x: x['count']))
print(sorted(d.values(), key=lambda x: x['price']))
from operator import itemgetter
print(sorted(d.values(), key=itemgetter('count')))
print(sorted(d.values(), key=itemgetter('price')))
print(sorted(d.values(), key=itemgetter('price', 'count')))
max min
l = ['hello', 'a', 'hjded', 'dederfref']
print(max(l, key=lambda x: len(x)))
print(min(l, key=lambda x: len(x)))
匿名函数
匿名函数定义规则: lambda 形参:返回值
def fun(*args, **kwargs):
return args, kwargs
print(lambda *args, **kwargs : (args, kwargs))
from functools import reduce
print(reduce(lambda x,y : x +y , [1,2,3,4,5]))
lambda
# 奇偶数排序
import random
li = [random.randint(1, 10) for i in range(10)]
print(li)
print(sorted(li, key=lambda x: 1 if x % 2 == 0 else 0))
print(sorted(li, key=lambda x: x%2==0))
#商品排序
info = [
# 商品名称 商品数量 商品价格
('apple3', 200, 32),
('apple4', 40, 12),
('apple1', 40, 2),
('apple2', 1000, 23),
] # 商品排序
print(sorted(info))
# 按照商品的数量进行排序, key代表排序的关键字
print(sorted(info, key=lambda x: x[1]))
# 按照商品的价格进行排序, key代表排序的关键字
print(sorted(info, key=lambda x:x[2]))
print(sorted(info, key=lambda x: (x[1], -x[2])))
itemgetter
from operator import itemgetter
print(sorted(info))
# 按照商品的数量进行排序, key代表排序的关键字
print(sorted(info, key=itemgetter(1)))
# 按照商品的价格进行排序, key代表排序的关键字
print(sorted(info, key=itemgetter(2)))
print(sorted(info, key=itemgetter(1,2)))
print(sorted(info, key=itemgetter(1,2)))
凯撒加密—加密算法
在密码学中,恺撒密码是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,
明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。
import string
# abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
# defghijklmnopqrstuvwxyzabc DEFGHIJKLMNOPQRSTUVWXYZABC
凯撒加密---加密算法的实现
def kaisacrypt(text='hello', k=3):
# 对原有小写字母向右移动k位
lower = string.ascii_lowercase[k:] + string.ascii_lowercase[:k]
upper = string.ascii_uppercase[k:] + string.ascii_uppercase[:k]
# 用于创建字符串映射的转换表'hello'
table = str.maketrans(string.ascii_letters, lower+upper)
# 根据转换表去转换对应的字符
return text.translate(table)
def check(text):
"""
思路:
测试文本中是否存在至少两个最常见的英文单词, 如果有, 则代表破解成功.
"""
mostCommonWords = ('the', 'is', 'to', 'not', 'have', 'than', 'for', 'ok', 'and' )
return len([1 for word in mostCommonWords if word in text])>2
暴力破解
def bruteForce(text):
for i in range(26):
# 1,2,3,4,5
t = kaisacrypt(text, -i)
if check(t):
print(i)
print(t)
break
text = "If not to the sun for smiling, warm is still in the sun there, but wewill laugh more confident calm; if turned to found his own shadow, appropriate escape, the sun will be through the heart,warm each place behind the corner; if an outstretched palm cannot fall butterfly, then clenched waving arms, given power; if I can't have bright smile, it will face to the sunshine, and sunshine smile together, in full bloom."
cryptStr = kaisacrypt(text=text, k=18)
print(cryptStr)
bruteForce(cryptStr)
ASCII码
ord('a')
Out[2]: 97
ord('d')
Out[3]: 100
chr(97)
Out[4]: 'a'
chr(100)
Out[5]: 'd'
基于缓冲区的生产者消费者模型
import random
import time
# 缓冲区列表, 存放生产的所有c产品,工作方式是队列的工作方式(FIFO-first in firest out).
cacheList = []
# 如果缓冲区列表的长度为5, 缓冲区就满了, 生产者不能再生产了.
cacheListLen = 5
def isfull():
# 缓冲区满了
return len(cacheList) == 5
def consumer(name):
"""消费者"""
print("%s准备购买产品......." %(name))
while True:
kind = yield
print("%s购买%s产品成功..." %(name, kind))
def producer(name):
print("%s人员正在生产产品......." %(name))
kinds = ['A', 'B', 'C', 'D']
while True:
if not isfull():
# 模拟生产数据耗费的时间
time.sleep(random.random())
kind = random.choice(kinds)
print("%s已经生产好%s产品了..." %(name, kind))
cacheList.append(kind)
else:
print("已经有足够的产品")
yield
p = producer("张三")
next(p)
consumers = [consumer('user'+str(i)) for i in range(10)]
for i in consumers:
if not cacheList:
print("目前没有产品")
else:
# 如果缓冲区没有满, 就让生产者继续生产产品, 丛上次停止的地方继续执行.
if not isfull():
next(p)
# 从缓冲区拿出产品给消费者.
kind = cacheList.pop()
next(i)
i.send(kind)