标签:学习笔记
装饰器应用练习def cache(fn):
import inspect
local_cache = {}
def wrapper(*args, **kwargs):
sig = inspect.signature(fn)
params = sig.parameters
param_names = list(params.keys())
temp_dict = {}
#处理位置参数
for k, v in enumerate(args):
temp_dict[param_names[k]] = v
#更新关键字参数值
temp_dict.update(kwargs)
#更新默认值
for k, v in params.items():
temp_dict[k] = v.default
#排序生成元组
temp_tuple = tuple(sorted(temp_dict.items()))
if temp_tuple not in local_cache.keys():
local_cache[temp_tuple] = fn(*args, **kwargs)
return local_cache[temp_tuple]
return wrapper
import time
@cache
def add(x, y, z):
time.sleep(2)
return x + y + z
import inspect
from datetime import datetime
def cache(duration):
def _cache(fn):
local_cache={}
def wrapper(*args, **kwargs):
def expire_cache(cache:dict):
expire_list = []
for k,(_,stamp) in cache.items():
delta = (datetime.now().timestamp() - stamp)
if delta > duration:
expire_list.append(k)
for k in expire_list:
cache.pop(k)
expire_cache(local_cache)
sig=inspect.signature(fn)
params=sig.parameters
param_names=list(params.keys())
param_dict={}
for k,v in enumerate(args):
param_dict[param_names[k]] = v
param_dict.update(kwargs)
for k, v in params.items():
if k not in param_dict.keys():
param_dict[k] = v.default
param_keys=tuple(sorted(param_dict.items()))
if param_keys not in local_cache.keys():
local_cache[param_keys]=(fn(*args,**kwargs), datetime.now().timestamp())
return local_cache[param_keys][0]
return wrapper
return _cache
def cmd_dispatcher(): #封装
cmd_dict = {}
def reg(cmd):
def _reg(fn):
cmd_dict[cmd] = fn
return fn
return _reg
@reg(‘default_func‘)
def default_func():
print(‘default‘)
return
def dispatcher():
while True:
cmd = input(‘>>‘)
if cmd == ‘quit‘:
return
cmd_dict.get(cmd, default_func)()
return reg, dispatcher #封装
reg, dispatcher = cmd_dispatcher() #封装&解构
@reg(‘add‘)
def add(): #add=reg(‘add‘)(add)
print(1)
return
dispatcher()
def show_tree(lst, unit_width=2):
from math import log2, ceil
length = len(lst)
depth = ceil(log2(length + 1))
width = 2 ** depth - 1
index= 0
for i in range(depth):
for j in range(2 ** i):
print(‘{:^{}}‘.format(lst[index], width * unit_width), end = ‘ ‘ * unit_width)
index += 1
if index >= length:
break
width //= 2
print()
from math import ceil, log2
#投影栅格实现
def print_tree(array):
‘‘‘
‘‘‘
index = 1
depth = ceil(log2(len(array)))
sep = ‘ ‘
for i in range(depth):
offset = 2 ** i
print(sep * (2 ** (depth - i -1) - 1), end = ‘‘)
line = array[index : index + offset]
for j, x in enumerate(line):
print("{:>{}}".format(x, len(sep)), end = ‘‘)
interval = 0 if i == 0 else 2 ** (depth - i) - 1
if j < len(line) - 1:
print(sep * interval, end = ‘‘)
index += offset
print()
def heap_sort(lst:list):
‘‘‘
堆排序
:type lst: list
:rtype: list
‘‘‘
length = len(lst)
lst.insert(0,0) # 前插0为了索引和结点号能够对应上,索引不必加一,便于理解,输出时切片即可
def heap_adjust(start, end):
‘‘‘
调整当前节点
调整结点的起点在n//2,保证所有调整结点都有孩子结点
:param end: 待比较个数
:param start: 当前节点下标
:rtype: None
‘‘‘
while 2 * start <= end: # 如果该结点下还有孩子则进入循环,否则跳出
lchild_index = 2 * start #该结点号*2 为左孩子结点
max_child_index = lchild_index #
if lchild_index < end and lst[lchild_index + 1] > lst[lchild_index]: # 如果有右孩子并且右孩子比左孩子的数大,则更新最大值索引
max_child_index = lchild_index + 1
if lst[max_child_index] > lst[start]: #孩子结点比较完后与父结点比较,最大值放到父结点,并且下一次迭代的父结点是本次最大孩子索引
lst[start], lst[max_child_index] = lst[max_child_index], lst[start]
start = max_child_index
else: # 如果父结点最大则直接跳出,因为排顶堆从编号最大的子树开始调整,即保证了本次最大孩子结点与其孩子结点已经形成了顶堆
break
for st in range(length//2, 0, -1): # 调整为大顶堆
heap_adjust(st, length)
for end in range(length, 1, -1): #sort排序 根结点与最后结点交换,每次迭代刨除最后结点,直至只剩根结点
lst[1], lst[end] = lst[end], lst[1]
heap_adjust(1, end - 1)
return lst[1:]
标签:学习笔记
原文地址:http://blog.51cto.com/11281400/2107790