Decorator Application Exercises One, implement a cache decorator, to achieve the ability to expire can be cleared
- Simplified design, the function's formal parameter definition does not contain the variable position parameter, the variable keyword parameter and the keyword-only parameter
- Can not consider the cache full after the change problem 1) original
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 wrapperimport time@cachedef add(x, y, z): time.sleep(2) return x + y + z
2) Add Expiration judgment
Import inspectfrom datetime Import datetimedef Cache (duration): def _cache (FN): local_cache={} def Wrappe R (*args, **kwargs): Def expire_cache (cache:dict): Expire_list = [] for k, (_,stamp ) in Cache.items (): Delta = (DateTime.Now (). Timestamp ()-stamp) if delta > Dura Tion: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 ()) re Turn Local_cache[param_keys][0] return wrapper return _cache
Second, write a command dispenser
- Programmers can easily register functions to a command, and when the user enters a command, it is routed to the registered function
- If this command does not have a corresponding registration function, execute the default function
- User input using input (">>")
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) returndispatcher()
Binary Tree Traversal Breadth-First traversal
- Sequence traversal, based on the level of the tree, from the first layer, from left to right traversal element depth first traversal
- The root node of the tree is D, the left subtree is L, the right subtree is r, and the requirement L must precede r, there are several ways to traverse:
- Pre-order traversal, also called first-order traversal, also called root traversal, DLR
- The middle sequence traversal, also called the middle root traversal, LDR
- Post-order traversal, also called after Root traversal, LRD
- Traversal sequence: The sequence of elements that are obtained after iterating through all the elements in the tree. Convert hierarchies to linear structures
Pre-order Traversal DLR
- Starting from the root node, first left subtree, right subtree.
- Within each subtree remains the first root node, and then the left subtree after the right sub-tree. Recursive traversal
- Traversing a sequence
Middle Sequence Traversal LDR
- Zuozi from the root node, then the root node, then the right subtree.
- Inside each subtree is also the first left subtree, the posterior root node, and then the right subtree. Recursive traversal
- Traversing a sequence
- Left image
- GDHB A IECF
- Right image
- GDHB A EICF
Post-Traversal LRD
- First left subtree, right sub-tree, then root node.
- Inside each subtree remains the first left subtree, then the right subtree, and then the root node. Recursive traversal
- Traversing a sequence
Heap Sort Heaps heap
- Heap is a completely binary tree
- Each non-leaf node must be greater than or equal to the value of its left and right child nodes called the Big Top heap.
- Each non-leaf node is less than or equal to the value of its left and right child nodes called the small top heap.
- The root node must be the maximum value in the large top heap, which must be the minimum value in the small top heap.
Big Top Pile
- Each non-leaf node of a complete binary tree is greater than or equal to the value of its left and right child nodes called the Big Top heap.
- The root node must be the maximum value in the Big Top heap.
Small Top Pile
- Each non-leaf node of a complete binary tree is less than or equal to the value of its left and right child nodes, called the small top heap.
- The root node must be the smallest value in the small top heap.
Theory Realization 1, construct complete binary tree
- The number to be sorted is 30,20,80,40,50,10,60,70,90
- Constructs a complete binary tree to store data, and according to the nature of 5 to the element number, into the sequential data structure
- Constructs a list of [0,30,20,80,40,50,10,60,70,90]
2. Building a big top heap--core algorithm
- The node A with a degree of 2, if its left and right child node maximum is larger than it, the maximum value and the node Exchange
- Node A with a degree of 1, if its left child's value is greater than it, then swap
- If Node A is swapped to a new location, it needs to repeat the process with the child's node.
2.1 Constructing the large top pile--the selection of the starting point node
- Starting from the parent node of the last node of the complete binary tree, that is, the node of the rightmost leaf node of the last layer begins the knot point N, then the starting node is numbered N//2 (property 5).
2.2 Building a large top heap--selection of the next node
- From the start node to the left to find its same layer node, the head and then start from the rightmost node of the previous layer to continue to look to the left, until the root node
2.3 goals of the big top pile
- Make sure that each node is larger than the value of the left and right node points
3. Sorting
- The largest heap root node this maximum and the last leaf node exchange, then the last leaf node is the maximum value, the leaf node is excluded from the point to be sorted
- Repeat the previous step, starting with the root node (new root node) and re-sizing to a large top heap
Code implementation 1. Print tree structure (not necessary, easy to see changes in tree structure for each step) 1) method One center alignment
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()
2) method two projection grid implementation
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()
2. Heap Sequencing implementation
def heap_sort (lst:list): "Heap Sort: Type Lst:list:rtype:list" "Length = Len (LST) Lst.insert (0,0) # 0 in order to index and node number can correspond, the index does not need to add one, easy to understand, the output of the chip can be Def heap_adjust (start, end): "Adjust the current node adjustment nodes starting point in the N//2, to ensure that all the adjustment knot There are children at all points:p Aram end: To compare the number:p Aram start: Current node subscript: Rtype:none "while 2 * start <= E Nd: # If there is a child under this node into the loop, otherwise jump out Lchild_index = 2 * Start #该结点号 * * For left child node Max_child_index = lchild_index # If Lchild_index < end and Lst[lchild_index + 1] > Lst[lchild_index]: # Update the Max index if there is a right child and the right child has a larger number than the left child Max_child_index = Lchild_index + 1 if Lst[max_child_index] > Lst[start]: #孩子结点比较完后与父结点比较, the maximum value is placed on the parent node, and and the parent node of the next iteration is the Max Child Index Lst[start], lst[max_child_index] = Lst[max_child_index], Lst[start] Star T = Max_child_index Else: # If the parent node is the largest, it jumps directly because the top heap is adjusted from the largest sub-tree, which guarantees that the maximum child node and its child nodes have formed a top heap break fo R St in range (LENGTH//2, 0,-1): # Adjusts to the large top heap heap_adjust (st, length) for end in range (length, 1,-1): #sort排序 root node is exchanged with the last node, each iteration shaving the last node until only the root node remains. LST[1], lst[end] = Lst[end], lst[1] heap_adjust (1, end-1) return lst[1:]
- Time complexity O (NLOGN), Average time complexity O (NLOGN)
- Space complexity O (1)
- Unstable sort
Python Fifth Week study notes (2)