├── .DS_Store ├── Books ├── .DS_Store ├── Python编程快速上手 让繁琐工作自动化.pdf ├── README.md ├── 《从零开始学 Python》(第二版) - v1.1.pdf ├── 利用Python进行数据分析(Python For Data Analysis中文版).pdf └── 利用Python进行数据分析.pdf ├── README.md ├── graph algorithm ├── Dynamic programming.py ├── GCD.py ├── README.md ├── binarySearch.py ├── bubbleSort.py ├── bubbleSort2.py ├── dichotomy.py ├── dijkstras_algorithm2.py ├── find_maxmum_subarray_alg.py ├── find_maxmum_subarray_algr.py ├── find_maxmum_subarray_lineartime_algr.py ├── greedy_algorithm.py ├── hashtable_list.py ├── inorder_tree.py ├── insertsort.py ├── list_implet_stack.py ├── list_tree.py ├── map_item.py ├── move_pyautogui.py ├── node_tree.py ├── numpy_array.py ├── numpy_save_use.py ├── numpy_ufunc.py ├── numpy_weave.py ├── par_check_stack.py ├── pars_check_stack.py ├── queue_hotpotato.py ├── queue_imple_by_list.py ├── quick_sort.py ├── quick_sort2.py ├── recursion.py ├── recursion_convert.py ├── recursion_turtle.py ├── rexursion_tree.py ├── scipy_odeint.py ├── select_sort.py ├── selectsort.py ├── sequentialSearch.py ├── seuqenSearch.py ├── shellsort.py ├── stack_binary_convert.py ├── sum.py ├── sum2.py ├── unorderdedlist_node.py └── word_match.py ├── items ├── README.md ├── changeInto9parts_pillow_item.py ├── changeToChar_pil_item.py ├── character_graph.py ├── copy_paste.py ├── find_text.py ├── findmaxmanmin.py ├── intersection_leecode.py ├── michelson_lightpipes.py ├── password.py ├── prc_list.py ├── random_test_paper_item.py ├── read_file.py ├── regex_find_emial_phonenumber.py ├── stopwatch_time_item.py ├── tictactoe_model.py ├── while_75.py └── word_match.py ├── python_ProcessFile └── README.md ├── python_fundamental ├── README.md ├── backup.py ├── backuprefresh.py ├── class.import.py ├── class.py ├── class_change.py ├── class_son9798.py ├── class_vari.py ├── creat_list.py ├── dict_dict.py ├── dict_list.py ├── dict_list2.py ├── fileobj_oarganisation.py ├── func2.py ├── func_dict87.py ├── func_keyfactors814.py ├── func_list811.py ├── function_default.py ├── function_global.py ├── function_return.py ├── input.py ├── map_reduce.py ├── module_running_name.py ├── module_using_sys.py ├── modules_dictionary.py ├── open_write_file_prc.py ├── prc.dict.py ├── prc_list2.py ├── prc_list_value.py ├── subclass.py ├── while_break.py ├── while_breaks.py ├── while_dict.py └── while_list.py └── python_lib ├── Matplotlib └── README.md ├── Numpy ├── README.md ├── numpy_array.py ├── numpy_save_use.py ├── numpy_ufunc.py └── numpy_weave.py ├── Pandas ├── 1.series数据结构.md ├── 2.DataFrame数据结构.md ├── DataFrame.html ├── README.md ├── picture │ ├── README.md │ ├── series定义-dict.png │ ├── series定义1.png │ ├── series对象.png │ ├── series通过索引修改.png │ ├── 修改series索引.png │ ├── 判断是否为空.png │ └── 添加索引.png └── test.ipynb ├── PyAutoGui ├── README.md ├── keyboard_control_pyautogui.py ├── mouse_control_pyautogui.py ├── move_pyautogui.py ├── screen_pyautogui.py └── screenshot_pyautogui.py ├── Time ├── README.md ├── datetime.py ├── time_round.py ├── time_sleep.py └── time_time.py └── Typing ├── README.md └── python-typing.ipynb /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LiuChuang0059/python_practise/930afb2b1f8818faebcb811811a8e97d61715738/.DS_Store -------------------------------------------------------------------------------- /Books/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LiuChuang0059/python_practise/930afb2b1f8818faebcb811811a8e97d61715738/Books/.DS_Store -------------------------------------------------------------------------------- /Books/Python编程快速上手 让繁琐工作自动化.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LiuChuang0059/python_practise/930afb2b1f8818faebcb811811a8e97d61715738/Books/Python编程快速上手 让繁琐工作自动化.pdf -------------------------------------------------------------------------------- /Books/README.md: -------------------------------------------------------------------------------- 1 | # python 学习相关书籍 2 | -------------------------------------------------------------------------------- /Books/《从零开始学 Python》(第二版) - v1.1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LiuChuang0059/python_practise/930afb2b1f8818faebcb811811a8e97d61715738/Books/《从零开始学 Python》(第二版) - v1.1.pdf -------------------------------------------------------------------------------- /Books/利用Python进行数据分析(Python For Data Analysis中文版).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LiuChuang0059/python_practise/930afb2b1f8818faebcb811811a8e97d61715738/Books/利用Python进行数据分析(Python For Data Analysis中文版).pdf -------------------------------------------------------------------------------- /Books/利用Python进行数据分析.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LiuChuang0059/python_practise/930afb2b1f8818faebcb811811a8e97d61715738/Books/利用Python进行数据分析.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | [1.python--基础学习](https://github.com/LiuChuang0059/python_practise/blob/master/python_fundamental/README.md) 4 | 5 | 6 | 7 | 8 | 9 | 10 | [2.python--小项目练习](https://github.com/LiuChuang0059/python_practise/blob/master/items/README.md) 11 | 12 | 13 | 14 | 15 | ----- 16 | 17 | [python 入门图书 PDF](https://github.com/LiuChuang0059/python_practise/tree/master/Books) 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /graph algorithm/Dynamic programming.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat May 26 18:21:35 2018 4 | 5 | @author: 刘闯 6 | 7 | 动态规划 8 | 在重量允许下 价格总和最大 9 | 10 | """ 11 | 12 | ##创建表示物品价格 和 重量的字典 13 | goods={} 14 | goods['guita']=[1,1500] 15 | goods['notebook']=[3,2000] 16 | goods['sounder']=[4,3000] 17 | 18 | ###数字和物品 对应字典 19 | num={} 20 | num[1]='guita' 21 | num[2]='notebook' 22 | num[3]='sounder' 23 | 24 | ###创建价格表格 25 | 26 | price={} 27 | for i in range(1,len(goods.keys())+1): 28 | for j in range(1,5): 29 | price[i][j]=0 30 | if goods[i][0]B 11 | def GCD(A,B): 12 | if A==0: 13 | gcd=B 14 | elif B==0: 15 | gcd=A 16 | else: 17 | return GCD(B,A%B) 18 | return gcd 19 | print(GCD(27,123)) 20 | -------------------------------------------------------------------------------- /graph algorithm/README.md: -------------------------------------------------------------------------------- 1 | # 《图解算法》 ---学习笔记 +++ code 2 | -------------------------------------------------------------------------------- /graph algorithm/binarySearch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Mon Jun 18 23:23:09 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 二分查找 10 | 11 | """ 12 | 13 | def binarySearch(list1,item): 14 | 15 | first = 0 16 | last = len(list1) - 1 17 | found = False 18 | 19 | while first < last and not found: 20 | midpoint = (first + last)//2 21 | if list1[midpoint] == item : 22 | found = True 23 | else: 24 | if midpoint > item : 25 | last = midpoint -1 26 | else: 27 | first = midpoint + 1 28 | 29 | return found 30 | 31 | 32 | 33 | """ 34 | 35 | ##递归 36 | 37 | def binarySearch(alist, item): 38 | if len(alist) == 0: 39 | return False 40 | else: 41 | midpoint = len(alist)//2 42 | if alist[midpoint]==item: 43 | return True 44 | else: 45 | if item alist[i+1]: 17 | temp = alist[i] 18 | alist[i] = alist[i+1] 19 | alist[i+1] = temp ##交换位置 20 | 21 | alist = [54,26,93,17,77,31,44,55,20] 22 | bubbleSort(alist) 23 | print(alist) 24 | -------------------------------------------------------------------------------- /graph algorithm/bubbleSort2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Mon Jun 25 23:18:47 2018 5 | 6 | @author: liuchuang 7 | """ 8 | 9 | def bubbleSort(alist): 10 | for passnum in range(len(alist)-1,0,-1): 11 | for i in range(passnum): 12 | if alist[i]>alist[i+1]: 13 | temp = alist[i] 14 | alist[i] = alist[i+1] 15 | alist[i+1] = temp 16 | 17 | alist = [54,26,93,17,77,31,44,55,20] 18 | bubbleSort(alist) 19 | print(alist) -------------------------------------------------------------------------------- /graph algorithm/dichotomy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu May 17 18:06:59 2018 4 | 5 | @author: 刘闯 6 | """ 7 | ##二分法搜寻有序数组数字位置 8 | 9 | def search_number(list,guess): 10 | low=0 11 | high=len(list)-1 12 | 13 | 14 | while low<=high : ##注意取等 15 | mid=(low+high)//2 ##返回伤的整数部分 16 | if guess==list[mid]: 17 | return mid 18 | elif guess< list[mid]: 19 | high=mid-1 20 | elif guess>list[mid]: 21 | low=mid+1 22 | else: 23 | return None 24 | 25 | list1=[1,3,4,6,7,8,9] 26 | print(search_number(list1,8)) 27 | print(search_number(list1,10)) -------------------------------------------------------------------------------- /graph algorithm/dijkstras_algorithm2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri May 25 22:17:22 2018 4 | 5 | @author: 刘闯 6 | 7 | 狄克斯特拉算法 8 | 9 | 10 | """ 11 | 12 | # the graph 13 | graph = {} 14 | graph["start"] = {} 15 | graph["start"]["a"] = 6 16 | graph["start"]["b"] = 2 17 | 18 | graph["a"] = {} 19 | graph["a"]["fin"] = 1 20 | 21 | graph["b"] = {} 22 | graph["b"]["a"] = 3 23 | graph["b"]["fin"] = 5 24 | 25 | graph["fin"] = {} 26 | 27 | # the costs table 28 | infinity = float("inf") 29 | costs = {} 30 | costs["a"] = 6 31 | costs["b"] = 2 32 | costs["fin"] = infinity 33 | 34 | # the parents table 35 | parents = {} 36 | parents["a"] = "start" 37 | parents["b"] = "start" 38 | parents["fin"] = None 39 | 40 | 41 | procceded=[] ### 标记过的节点 42 | 43 | 44 | 45 | def find_lowest_cost_node(costs): ###找到最近的节点 46 | lowest_cost=float("inf") ##无穷 节点消耗 47 | lowest_cost_node=None ###节点 48 | for n in costs: 49 | cost=costs[n] 50 | if cost < lowest_cost and n not in procceded: 51 | lowest_cost=cost 52 | lowest_cost_node=n 53 | return lowest_cost_node 54 | 55 | 56 | node=find_lowest_cost_node(costs) 57 | while node is not None: ###遍寻所有节点 58 | cost=costs[node] ###节点消耗 59 | neighbors=graph[node] ###节点邻居 60 | for n in neighbors.keys(): ###节点邻居消耗更新 61 | new_cost=cost+neighbors[n] 62 | if new_cost < costs[n] : 63 | costs[n]=new_cost 64 | parents[n]=node ###更新父节点 65 | procceded.append(node) ### 去除节点 66 | node=find_lowest_cost_node(costs) 67 | 68 | print(costs) 69 | print(cost) 70 | print(parents) 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /graph algorithm/find_maxmum_subarray_alg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Jun 5 16:16:52 2018 5 | 6 | @author: liuchuang 7 | 8 | 最大子数组问题 9 | 10 | """ 11 | 12 | def Find_Max_Crossing_Subarray(A,low,mid,high): 13 | if len(A)/2==0: 14 | mid=int(len(A)/2) 15 | else: 16 | mid=int((len(A)-1)/2) 17 | left_sum=float('-inf') 18 | sum=0 19 | left_index=mid 20 | list1=list(range(mid+1)) 21 | list1.reverse() 22 | for i in list1: 23 | sum=sum+A[i] 24 | if sum> left_sum : 25 | left_sum=sum 26 | left_index=i 27 | right_sum=float('-inf') 28 | sum=0 29 | right_index=mid+1 30 | for j in range(mid+1,high+1): 31 | sum=sum+A[j] 32 | if sum> right_sum : 33 | right_sum=sum 34 | right_index=j 35 | return(left_index,right_index,left_sum+right_sum) 36 | A=[-2,3,4,-1,-5,4,-5] 37 | print(Find_Max_Crossing_Subarray(A,0,3,6)) -------------------------------------------------------------------------------- /graph algorithm/find_maxmum_subarray_algr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Jun 5 18:42:32 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 最大子数组 10 | 11 | """ 12 | from find_maxmum_subarray_alg import Find_Max_Crossing_Subarray as fmcs 13 | 14 | def Find_Maxmum_Subarray(A,low,high): 15 | ##基本情况 16 | if high==low: 17 | return (low,high,A[low]) 18 | else: 19 | 20 | mid=int((low+high)/2) 21 | """ 22 | left_low=Find_Maxmum_Subarray(A,low,mid)[0] 23 | left_high=Find_Maxmum_Subarray(A,low,mid)[1] 24 | left_sum=Find_Maxmum_Subarray(A,low,mid)[2] 25 | right_low=Find_Maxmum_Subarray(A,mid+1,high)[0] 26 | right_high=Find_Maxmum_Subarray(A,mid+1,high)[1] 27 | right_sum=Find_Maxmum_Subarray(A,mid+1,high)[2] 28 | cross_low=fmcs(A,low,mid,high)[0] 29 | cross_high=fmcs(A,low,mid,high)[1] 30 | cross_sum=fmcs(A,low,mid,high)[2] 31 | """ 32 | 33 | ### 左数组 34 | (left_low,left_high,left_sum)=Find_Maxmum_Subarray(A,low,mid) 35 | ###右数组 36 | (right_low,right_high,right_sum)=Find_Maxmum_Subarray(A,mid+1,high) 37 | ### 包含中点 调用 38 | (cross_low,cross_high,cross_sum)=fmcs(A,low,mid,high) 39 | 40 | ####比较 41 | if left_sum>=right_sum and left_sum>=cross_sum: 42 | return (left_low,left_high,left_sum) 43 | elif right_sum>=left_sum and right_sum>=cross_sum: 44 | return(right_low,right_high,right_sum) 45 | else: 46 | return(cross_low,cross_high,cross_sum) 47 | 48 | A=[-1,-3,3,4,6,3,4,53,-4,-7,4,5,6,-5,-6] 49 | print(Find_Maxmum_Subarray(A,1,12)) -------------------------------------------------------------------------------- /graph algorithm/find_maxmum_subarray_lineartime_algr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Jun 5 20:13:40 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 线性时间求解 最大子数组 10 | """ 11 | 12 | def Find_Maxmum_Subarray(A, low, high): 13 | left=0 14 | right=0 15 | sum = A[low] 16 | tempSum = 0 17 | for i in range(low,high+1): 18 | tempSum = max(A[i],tempSum+A[i]) 19 | if tempSum>sum: 20 | sum = tempSum 21 | right = i 22 | elif tempSum == A[i]: 23 | left = i 24 | return (left,right,sum) 25 | A=[1,-2,3,4,-4,5,6,-4,5] 26 | print(Find_Maxmum_Subarray(A,0,8)) 27 | 28 | -------------------------------------------------------------------------------- /graph algorithm/greedy_algorithm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat May 26 12:21:04 2018 4 | 5 | @author: 刘闯 6 | 7 | 贪婪算法 greedy 8 | 9 | 求解全覆盖 所需要最少的点 10 | 11 | """ 12 | 13 | #需要的数字集合 14 | number_needed=set([3,5,6,7,8]) 15 | 16 | #字母包含的数字 17 | 18 | graph={} 19 | graph['A']=set([1,2,3,4]) 20 | graph['B']=set([2,3,5]) 21 | graph['C']=set([3,5,6]) 22 | graph['D']=set([3,7,8,2]) 23 | 24 | #需要最少的字母列表 25 | char_selection=[] 26 | 27 | #循环 直到 需要的字母集合为空 28 | while number_needed : 29 | best_char=None 30 | ##字母包含的数字和需要数字的集合 31 | number_covered=set() 32 | 33 | for char, num in graph.items(): 34 | covered=num & number_needed 35 | if len(covered) > len(number_covered): 36 | number_covered=covered 37 | best_char=char 38 | ##添加 重合最多的字母 39 | char_selection.append(best_char) 40 | ###从待需要集合 减去 选出的数字 41 | number_needed=number_needed-number_covered 42 | 43 | print(char_selection) 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /graph algorithm/hashtable_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Mon Jun 18 23:40:59 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 两个列表 实现 一个 HashTable 10 | 11 | 一个保存 key 值 12 | 一个保存 value值 13 | 14 | """ 15 | 16 | class HashTable: 17 | """ 18 | hash 函数为余数 除法hash 19 | 冲突解决方法 +1 后 rehash 重新探测 20 | """ 21 | 22 | def __init__(self): 23 | self.size = 5 ###hash 初始的大小 24 | self.slots = [None] * self.size ## 11个空位置 25 | self.data = [None] * self.size 26 | 27 | 28 | def put(self,key,value): 29 | """ 30 | 插入key--value 31 | """ 32 | hashvalue = self.hashfunction(key,len(self.slots)) 33 | ##计算hash值 34 | 35 | if self.slots[hashvalue] == None: 36 | ###如果哈希值为对应key列表的位置为空 37 | self.slots[hashvalue] = key ## 直接插入 38 | self.data[hashvalue] = value 39 | 40 | else: 41 | ###如果已经存在数值 42 | if self.slots[hashvalue] == key: 43 | ###如果key 已经存在 在self.slots?? 44 | self.data[hashvalue] = value 45 | ### 新的值替换 46 | else: 47 | nextslot = self.rehash(hashvalue,len(self.slots)) 48 | ###rehash 向下排一位 49 | while self.slots[nextslot] != None and \ 50 | self.slots[nextslot] !=key: 51 | nextslot = self.rehash(nextslot,len(self.slots)) 52 | 53 | 54 | 55 | if self.slots[nextslot] == None: 56 | self.slots[nextslot] =key 57 | self.data[nextslot] = value 58 | 59 | else: 60 | self.data[nextslot] = value 61 | 62 | 63 | def hashfunction(self,key,size): 64 | return key % size 65 | 66 | 67 | def rehash(self,oldhash,size): 68 | return (oldhash+1)%size 69 | 70 | 71 | 72 | def get(self,key): 73 | """ 74 | 查找key值 75 | """ 76 | startslot = self.hashfunction(key,len(self.slots)) 77 | 78 | 79 | data = None 80 | stop = False 81 | found = False 82 | 83 | position = startslot 84 | 85 | 86 | while self.slots[position] != None and not stop and not found: 87 | 88 | if self.slots[position] == key: 89 | found = True 90 | data= self.data[position] 91 | 92 | else: 93 | ##调用rehash 定位下一个位置 94 | position = self.rehash(position,len(self.slots)) 95 | 96 | if position == startslot: 97 | ### 返回到初始槽 用尽所有槽 98 | stop = True 99 | 100 | return data 101 | 102 | 103 | def __getitem__(self,key): 104 | return self.get(key) 105 | 106 | def __setitem__(self,key,data): 107 | self.put(key,data) 108 | 109 | 110 | 111 | H = HashTable() 112 | 113 | H[1]="A" 114 | H[2]="B" 115 | H[3]="C" 116 | H[4]="D" 117 | H[5]="E" 118 | H[1]="a" 119 | 120 | print(H.data) 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /graph algorithm/inorder_tree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Fri Jun 8 00:20:40 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 树的遍历 10 | 11 | 前序 12 | 中序 13 | 后 14 | 15 | """ 16 | 17 | 18 | def preorder(tree): 19 | ''' 20 | 外部函数编写 21 | 前序遍历 22 | ''' 23 | if tree: 24 | print(tree.GetRootVal()) 25 | preorder(tree.GetLeftChild()) 26 | preorder(tree.GetRightChild()) 27 | 28 | 29 | def inorder(tree): 30 | ''' 31 | 中序遍历 32 | ''' 33 | if tree != None: 34 | inorder(tree.GetLeftChild()) 35 | print(tree.GetRootVal()) 36 | inorder(tree.GetRightChild()) 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /graph algorithm/insertsort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Jun 26 00:17:01 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 插入排序 10 | n-1 次比较 11 | 12 | O(n^2) 13 | 14 | 但是仅仅进行一次分配 15 | """ 16 | 17 | def insertSort(alist): 18 | for index in range(1,len(alist)): 19 | ##遍历列表 20 | current = alist[index] 21 | position = index 22 | 23 | while position > 0 and alist[position-1] > current: 24 | ###向左移动比较 如果小 就移位 直到大 25 | alist[position] = alist[position - 1] 26 | position = position -1 27 | 28 | alist[position]= current 29 | 30 | 31 | alist = [54,26,93,17,77,31,44,55,20] 32 | insertSort(alist) 33 | print(alist) -------------------------------------------------------------------------------- /graph algorithm/list_implet_stack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Fri Jun 8 01:06:29 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 列表实现栈 10 | 11 | """ 12 | 13 | class Stack: 14 | ''' 15 | 栈的操作 类 16 | ''' 17 | def __init__(self): 18 | ### 19 | self.items = [] 20 | 21 | 22 | def isEmpty(self): 23 | ###判断是否为空栈 返回布尔值 24 | return self.items == [] 25 | 26 | 27 | def push(self,item): 28 | ## 压入 元素 添加到队尾 29 | self.items.append(item) 30 | 31 | 32 | def pop(self): 33 | ###从队尾删除 34 | return self.items.pop() 35 | 36 | 37 | def peek(self): 38 | ###返回栈顶部值 39 | return self.items[len(self.items)-1] 40 | 41 | 42 | def size(self): 43 | ###栈的大小 44 | return len(self.items) 45 | 46 | 47 | from pythonds.basic.stack import Stack 48 | 49 | ### 实例化 50 | s=Stack() 51 | print(s.isEmpty()) 52 | s.push(4) 53 | s.push('dog') 54 | print(s.peek()) 55 | s.push(True) 56 | print(s.size()) 57 | print(s.isEmpty()) 58 | s.push(8.4) 59 | print(s.pop()) 60 | print(s.pop()) 61 | print(s.size()) 62 | -------------------------------------------------------------------------------- /graph algorithm/list_tree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Jun 7 20:33:02 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | use list to implement tree 10 | 11 | . 12 | """ 13 | 14 | import pprint 15 | 16 | 17 | Mytree=['a', ##root 18 | ['b', ## leftchild left_subtree 19 | ['d',[],[]], 20 | ['e',[],[]]], 21 | ['c', ### 1st rightchild righr sub-tree 22 | ['f',[],[]]] 23 | ] 24 | ####Mytree[0]: root Mytree[1] leftsubtree Mytree[2]: right_subtree 25 | pprint.pprint(Mytree) 26 | print(Mytree[1]) 27 | print(Mytree[2]) 28 | 29 | 30 | def BinaryTree(r): 31 | ###构造一个具有根结点和两个子列表为空 32 | return [r,[],[]] 33 | 34 | 35 | def InsertLeftBranch(root,newBranch): 36 | ###添加左子树 37 | t = root.pop(1) 38 | if len(t) > 1: 39 | ##左child有值 40 | root.insert(1,[newBranch,t,[]]) 41 | else: 42 | root.insert(1,[newBranch,[],[]]) 43 | 44 | 45 | def InsertRightBranch(root,newBranch): 46 | ###添加右子树 47 | t = root.pop(2) 48 | if len(t) > 1: 49 | ##左child有值 50 | ###原值一定在newbranch 右边 51 | root.insert(2,[newBranch,[],t]) 52 | else: 53 | root.insert(2,[newBranch,[],[]]) 54 | 55 | 56 | def GetRootValue(root): 57 | ### 获取根结点值 58 | return root[0] 59 | 60 | 61 | def SetRootValue(root,newVal): 62 | root[0]=newVal 63 | 64 | 65 | def GetLeftChild(root): 66 | ### get the left subtree 67 | return root[1] 68 | 69 | def GetRightChild(root): 70 | ### get the right subtree 71 | return root[2] 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /graph algorithm/map_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Jun 28 18:14:12 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | """ 10 | 11 | import webbrowser,sys, pyperclip 12 | 13 | if len(sys.argv) > 1: 14 | address = ' '.join(sys.argv[1:]) 15 | 16 | else: 17 | address = pyperclip.paste() 18 | 19 | 20 | webbrowser.open('http://www.google.com/maps/place/' + address) -------------------------------------------------------------------------------- /graph algorithm/move_pyautogui.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 27 00:04:39 2018 5 | 6 | @author: liuchuang 7 | 8 | 控制鼠标移动 9 | """ 10 | import pyautogui 11 | 12 | 13 | ### 1 移动鼠标 14 | for i in range(10): 15 | pyautogui.moveTo(100,100,duration=1.0)###移动到指定的像素点 16 | pyautogui.moveTo(150,200,duration=1.0) 17 | pyautogui.moveTo(250,100,duration=1.0) 18 | 19 | 20 | for i in range(10): 21 | pyautogui.moveRel(1000,0,duration=0.25) ### 移动多少像素点 22 | pyautogui.moveRel(0,800,duration=0.25) 23 | pyautogui.moveRel(-1000,0,duration=0.25) 24 | pyautogui.moveRel(0,-800,duration=0.25) 25 | 26 | 27 | ### 2 获取鼠标位置 28 | 29 | a=pyautogui.position() ##返回鼠标位置元祖 30 | -------------------------------------------------------------------------------- /graph algorithm/node_tree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Jun 7 21:37:56 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | use node to implement tree 10 | 11 | 12 | """ 13 | import list_tree 14 | 15 | class BinaryTree: 16 | def __init__(self,rootobj): 17 | #### 树的根对象 可以是对任何对象的引用 18 | self.key=rootobj 19 | self.leftchild=None 20 | self.rightchild=None 21 | 22 | def InsertLeftChild(self,newNode): 23 | ''' 24 | add left subtree 25 | create a new binary object 26 | use self.leftchild to merge it 27 | ''' 28 | if self.leftchild == None: 29 | self.leftchild = BinaryTree(newNode) 30 | else: 31 | t = BinaryTree(newNode) 32 | ### add old node into the left of t (next layer) 33 | t.leftchild = self.leftchild 34 | ### add t into left of root 35 | self.leftchild = t 36 | 37 | 38 | def InsertRightChild(self,newNode): 39 | ''' 40 | add left subtree 41 | create a new binary object 42 | use self.leftchild to merge it 43 | ''' 44 | if self.rightchild == None: 45 | self.rightchild = BinaryTree(newNode) 46 | else: 47 | t = BinaryTree(newNode) 48 | ### add old node into the left of t (next layer) 49 | t.rightchild = self.rightchild 50 | ### add t into left of root 51 | self.rightchild = t 52 | 53 | 54 | def GetRightChild(self): 55 | ### get the value of right child 56 | return self.rightchild 57 | 58 | def GetLeftChild(self): 59 | ### 60 | return self.leftchild 61 | 62 | def SetRootVal(self,obj): 63 | self.key=obj 64 | 65 | def GetRootVal(self): 66 | return self.key 67 | 68 | r=BinaryTree('a') 69 | print(r.GetRootVal()) 70 | print(r.GetLeftChild()) 71 | 72 | r.InsertLeftChild('b') 73 | print(r.GetLeftChild()) 74 | print(r.GetLeftChild().GetRootVal()) 75 | 76 | r.InsertRightChild('c') 77 | print(r.GetRightChild()) 78 | print(r.GetRightChild().GetRootVal()) 79 | r.GetRightChild().SetRootVal('hello world') 80 | print(r.GetRightChild().GetRootVal()) 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /graph algorithm/numpy_array.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Jun 12 00:50:33 2018 5 | 6 | @author: liuchuang 7 | """ 8 | import numpy as np 9 | 10 | 11 | 12 | a= np.array([1,2,3])## 一位数组 13 | print(type(a)) 14 | print(a.shape) ###数组大小 15 | print(a[0]) 16 | 17 | a[0]=5 18 | print(a) 19 | 20 | 21 | b=np.array([[1,2,3],[4,5,6]]) ##二维数组 22 | print(b.shape) 23 | print(b[0,1],b[1,1]) 24 | print(b) 25 | 26 | print('\n\n' ) 27 | 28 | c=np.zeros((2,2)) 29 | print(c) 30 | print('\n') 31 | 32 | d=np.ones((1,2)) 33 | print(d) 34 | print('\n') 35 | 36 | 37 | e=np.full((3,3),7) 38 | print(e) 39 | print('\n') 40 | 41 | f =np.eye(2) 42 | print(f) 43 | print('\n') 44 | 45 | 46 | g=np.random.random((2,2)) 47 | print(e) 48 | 49 | 50 | h=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) 51 | 52 | #use slicing to pull out subarray 53 | 54 | k=h[:2,1:3] 55 | 56 | 57 | 58 | h.shape=4,3 59 | h.shape=2,-1### -1 时自动计算轴的长度 60 | 61 | l=h.reshape((6,2))##数组l,h 共享数据储存内存区域 62 | print(l) 63 | 64 | 65 | 66 | 67 | print(h) 68 | print('\n\n') 69 | 70 | print(k) 71 | 72 | 73 | ####???? 74 | row_r1 = h[1, :] # Rank 1 view of the second row of a 75 | row_r2 = h[1:2, :] # Rank 2 view of the second row of a 76 | print(row_r1, row_r1.shape) # Prints "[5 6 7 8] (4,)" 77 | print(row_r2, row_r2.shape) # Prints "[[5 6 7 8]] (1, 4)" 78 | 79 | # We can make the same distinction when accessing columns of an array: 80 | col_r1 = h[:, 1] 81 | col_r2 = h[:, 1:2] 82 | print(col_r1, col_r1.shape) # Prints "[ 2 6 10] (3,)" 83 | print(col_r2, col_r2.shape) 84 | 85 | 86 | 87 | 88 | ### 数组的元素类型 89 | 90 | array_type=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]],dtype=np.float) 91 | 92 | print(array_type) 93 | 94 | array_type2=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]],dtype=np.complex) 95 | print(array_type2) 96 | 97 | 98 | ### 创建数组的元素 99 | 100 | #### 1 arange ===range (开始,终止 ,步长) 101 | array1 = np.arange(0,1,0.1) 102 | print(array1) 103 | 104 | 105 | #### 2 linespace (开始,终止,元素个数)默认包含终止值(endpoint) 106 | array2 = np.linspace(0,1,10) 107 | print(array2) 108 | 109 | 110 | #### 3 logspace 等比 111 | array3 = np.logspace(0,3,33) 112 | print(array3) 113 | 114 | 115 | ### 字节序列创建数组 116 | s = "abcdefgh" 117 | 118 | 119 | #### 1 字符串为字节序列,每个字符占一个字节 120 | s_int8 = np.fromstring(s,dtype = np.int8) 121 | 122 | #### 2 16bit 两个相邻字节为一个整数 123 | s_int16 = np.fromstring(s,dtype = np.int16) 124 | 125 | #### 3 64位 双精度浮点数数组 126 | s_float = np.fromstring(s, dtype = np.float) 127 | 128 | 129 | print(s_int8,s_int16,s_float) 130 | 131 | 132 | ### 二维数组创建乘法表 133 | def func(i,j): 134 | return (i+1)*(j+1) 135 | 136 | a = np.fromfunction(func,(9,9)) 137 | ### 第一个参数 为计算每个数组元素的函数,, 138 | ### 第二个参数 序列 数组大小 139 | 140 | print(a) 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | -------------------------------------------------------------------------------- /graph algorithm/numpy_save_use.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 13 00:14:35 2018 5 | 6 | @author: liuchuang 7 | """ 8 | 9 | 10 | import numpy as np 11 | 12 | 13 | a = np.arange(10) 14 | 15 | ### 1 通过下标范围产生数组 和原数组共享数据空间 16 | b=a[::-1] ## 步长为负数 倒序 17 | c=a[3:7] ### 左开右闭 18 | 19 | 20 | ### 2 通过整数序列 元素选取 每个元素作为下标 获得新数组 不共享空间 21 | 22 | d=a[[1,2,3,5]] 23 | a[[1,2,3]]=4,5,6 24 | 25 | 26 | print(a,b,c,d) 27 | 28 | 29 | ### 3 布尔数组 30 | 31 | e = np.arange(3) 32 | f=e[np.array([True,False,True])] 33 | print('\n\n') 34 | print(f) -------------------------------------------------------------------------------- /graph algorithm/numpy_ufunc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 13 00:46:16 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | ufunc是universal function的缩写, 10 | 它是一种能对数组的每个元素进行操作的函数。 11 | NumPy内置的许多ufunc函数都是在C语言级别实现的, 12 | 因此它们的计算速度非常快。 13 | """ 14 | 15 | import numpy as np 16 | 17 | 18 | x = np.linspace(0,2*np.pi,10) 19 | 20 | y=np.sin(x) 21 | ###它对x中的每个元素求正弦值,然后将结果返回,并且赋值给y。 22 | ###计算之后x中的值并没有改变,而是新创建了一个数组保存结果 23 | ## 24 | print(y) 25 | 26 | 27 | -------------------------------------------------------------------------------- /graph algorithm/numpy_weave.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 13 13:26:00 2018 5 | 6 | @author: liuchuang 7 | """ 8 | 9 | import scipy.weave as weave 10 | import numpy as np 11 | import time 12 | 13 | def my_sum(a): 14 | n=int(len(a)) 15 | code=""" 16 | int i; 17 | 18 | double counter; 19 | counter =0; 20 | for(i=0;i 1: 31 | for i in range(num): 32 | simqueue.enqueue(simqueue.dequeue()) 33 | ### 队首删除添加到队尾 34 | 35 | simqueue.dequeue() 36 | ####返回最后 剩余的 37 | 38 | return simqueue.dequeue() 39 | 40 | 41 | namelist = ['a','b','c','d','e','f','g','h','i'] 42 | print(hotPotato(namelist,10)) 43 | 44 | -------------------------------------------------------------------------------- /graph algorithm/queue_imple_by_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 13 21:42:37 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 列表 实现队列 10 | 11 | 12 | """ 13 | 14 | class Queue(): 15 | """ 16 | 假定 队尾在列表的位置为0 17 | 删除队首 即是 列表的最后一个元素 18 | 19 | """ 20 | 21 | 22 | 23 | def __init__(self): 24 | self.items = [] 25 | 26 | 27 | def isEmpty(self): 28 | return self.items == [] 29 | 30 | 31 | def enqueue(self,item): 32 | self.items.insert(0,item) 33 | #### 列表0的位置插入 元素 34 | 35 | def dequeue(self): 36 | return self.items.pop() 37 | 38 | 39 | def size(self): 40 | return len(self.items) 41 | 42 | 43 | 44 | q=['2','3','4'] 45 | q = Queue() 46 | 47 | print(q.isEmpty()) 48 | 49 | 50 | q.enqueue(34) 51 | 52 | q.enqueue('23') 53 | 54 | print('\n') 55 | print(q.size()) 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /graph algorithm/quick_sort.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri May 18 12:43:53 2018 4 | 5 | @author: 刘闯 6 | 7 | 快速排序 8 | 9 | """ 10 | def quicksort(array): 11 | if len(array) < 2: 12 | # base case, arrays with 0 or 1 element are already "sorted" 13 | return array 14 | else: 15 | # recursive case 16 | pivot = array[0] 17 | # sub-array of all the elements less than the pivot 18 | less = [i for i in array[1:] if i <= pivot] 19 | # sub-array of all the elements greater than the pivot 20 | greater = [i for i in array[1:] if i > pivot] 21 | return quicksort(less) + [pivot] + quicksort(greater) 22 | list=[1,2,3,4,5,6,7,8,9,0,9,8,7,76666,5,4,3,3,2,2222222222,3334,4,5,5,4,3,4,2,3,4,5,6,34,565,34,3,454,6,6,5,7,5,7,6564,4] 23 | print(quicksort(list)) 24 | list.sort() 25 | print(list) -------------------------------------------------------------------------------- /graph algorithm/quick_sort2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri May 18 12:59:27 2018 4 | 5 | @author: 刘闯 6 | 7 | 快速排序 8 | """ 9 | 10 | def quick_sort(arr): 11 | if len(arr) <2: 12 | return arr 13 | else: 14 | list1=[] 15 | list2=[] 16 | for i in arr[1:]: 17 | if i >= arr[0]: 18 | list1.append(i) 19 | else: 20 | list2.append(i) 21 | return quick_sort(list2)+[arr[0]] +quick_sort(list1) 22 | 23 | list4=[13,4,3,2,3,9,3,4,5,6,76,7,3,4,5,6,6,7,8] 24 | print(quick_sort(list4)) 25 | 26 | ##重复元素无法排序 27 | -------------------------------------------------------------------------------- /graph algorithm/recursion.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sun Jun 17 01:14:36 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 将这个大三角形分成四个新的三角形。 10 | 忽略刚刚创建的中间三角形, 11 | 对三个小三角形中的每一个应用相同的过程 12 | 13 | """ 14 | 15 | import turtle 16 | 17 | def drawTriangle(points,color,myTurtle): 18 | myTurtle.fillcolor(color) 19 | myTurtle.up() 20 | myTurtle.goto(points[0][0],points[0][1]) 21 | myTurtle.down() 22 | myTurtle.begin_fill() ###填充三角形 23 | myTurtle.goto(points[1][0],points[1][1]) 24 | myTurtle.goto(points[2][0],points[2][1]) 25 | myTurtle.goto(points[0][0],points[0][1]) 26 | myTurtle.end_fill() 27 | 28 | def getMid(p1,p2): 29 | """ 30 | 接受两个端点为参数,返回他们的中点 31 | 32 | """ 33 | return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2) 34 | 35 | def sierpinski(points,degree,myTurtle): 36 | colormap = ['blue','red','green','white','yellow', 37 | 'violet','orange'] 38 | drawTriangle(points,colormap[degree],myTurtle) 39 | if degree > 0: 40 | sierpinski([points[0], 41 | getMid(points[0], points[1]), 42 | getMid(points[0], points[2])], 43 | degree-1, myTurtle) 44 | sierpinski([points[1], 45 | getMid(points[0], points[1]), 46 | getMid(points[1], points[2])], 47 | degree-1, myTurtle) 48 | sierpinski([points[2], 49 | getMid(points[2], points[1]), 50 | getMid(points[0], points[2])], 51 | degree-1, myTurtle) 52 | 53 | def main(): 54 | myTurtle = turtle.Turtle() 55 | myWin = turtle.Screen() 56 | myPoints = [[-100,-50],[0,100],[100,-50]] 57 | sierpinski(myPoints,4,myTurtle) 58 | myWin.exitonclick() 59 | 60 | main() -------------------------------------------------------------------------------- /graph algorithm/recursion_convert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Fri Jun 15 23:41:12 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 10 | 递归 解决 11 | 12 | 13 | 整数转化为任意进制的字符串 14 | 15 | 16 | """ 17 | 18 | def convert(n,base): 19 | convertstring = "0123456789ABCDEF" 20 | if n < base : ###基本条件 21 | return convertstring[n] 22 | else: ###递归调用 23 | return convert(n//base,base) + convertstring[n%base] 24 | 25 | print(convert(6137,2)) -------------------------------------------------------------------------------- /graph algorithm/recursion_turtle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Fri Jun 15 23:57:28 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 10 | 11 | 可视化递归 12 | 13 | turtle 模块 14 | 15 | 龟图形 16 | 17 | 18 | 19 | """ 20 | 21 | import turtle 22 | 23 | 24 | myTurtle = turtle.Turtle() 25 | mywin = turtle.Screen() #### 创建一个窗口 26 | 27 | 28 | def drawSpiral(myTurtle,linelen): 29 | if linelen > 0: 30 | myTurtle.forward(linelen) 31 | myTurtle.right(120) 32 | drawSpiral(myTurtle,linelen-5) 33 | 34 | drawSpiral(myTurtle,100) 35 | mywin.exitonclick() 36 | ### 方便的缩小窗口的方法 -------------------------------------------------------------------------------- /graph algorithm/rexursion_tree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sat Jun 16 00:13:58 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 递归 实现 分型树 10 | 11 | 12 | """ 13 | import turtle 14 | 15 | 16 | def tree(branchlen,t): 17 | if branchlen > 5 : 18 | t.forward(branchlen) 19 | t.right(20) 20 | tree(branchlen-15,t) 21 | t.left(40) 22 | tree(branchlen-15,t) 23 | t.right(20) 24 | t.backward(branchlen) 25 | 26 | 27 | def main(): 28 | t = turtle.Turtle() 29 | mywin = turtle.Screen() 30 | t.left(90) 31 | t.up() 32 | t.backward(100) 33 | t.down() 34 | t.color("green") 35 | tree(75,t) 36 | mywin.exitonclick() 37 | 38 | main() -------------------------------------------------------------------------------- /graph algorithm/scipy_odeint.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 13 13:05:24 2018 5 | 6 | @author: liuchuang 7 | """ 8 | 9 | from scipy.integrate import odeint 10 | import numpy as np 11 | 12 | def lorenz(w, t, p, r, b): 13 | # 给出位置矢量w,和三个参数p, r, b计算出 14 | # dx/dt, dy/dt, dz/dt的值 15 | x, y, z = w 16 | # 直接与lorenz的计算公式对应 17 | return np.array([p*(y-x), x*(r-z)-y, x*y-b*z]) 18 | 19 | t = np.arange(0, 30, 0.01) # 创建时间点 20 | # 调用ode对lorenz进行求解, 用两个不同的初始值 21 | 22 | """ 23 | 24 | lorenz, 它是计算某个位移上的各个方向的速度(位移的微分) 25 | (0.0, 1.0, 0.0),位移初始值。计算常微分方程所需的各个变量的初始值 26 | t, 表示时间的数组,odeint对于此数组中的每个时间点进行求解,得出所有时间点的位置 27 | args, 这些参数直接传递给lorenz函数,因此它们都是常量 28 | """ 29 | track1 = odeint(lorenz, (0.0, 1.00, 0.0), t, args=(10.0, 28.0, 3.0)) 30 | track2 = odeint(lorenz, (0.0, 1.08, 0.0), t, args=(10.0, 28.0, 3.0)) 31 | 32 | # 绘图 33 | from mpl_toolkits.mplot3d import Axes3D 34 | import matplotlib.pyplot as plt 35 | 36 | fig = plt.figure() 37 | ax = Axes3D(fig) 38 | ax.plot(track1[:,0], track1[:,1], track1[:,2]) 39 | ax.plot(track2[:,0], track2[:,1], track2[:,2]) 40 | plt.show() -------------------------------------------------------------------------------- /graph algorithm/select_sort.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu May 17 22:36:20 2018 4 | 5 | @author: 刘闯 6 | 7 | 选择排序 8 | 9 | """ 10 | 11 | #遍历 寻找最小值 12 | def find_smallest(arr): 13 | smallest=arr[0] 14 | smallest_index=0 15 | for i in range(0,len(arr)):## range到len-1 16 | if smallest>=arr[i]: 17 | smallest=arr[i] 18 | smallest_index=i 19 | return smallest_index 20 | 21 | 22 | #将最小值 依次放入新的列表 23 | 24 | def select_sort(arr): 25 | new_arr=[] 26 | while len(arr)>0: 27 | s=find_smallest(arr) 28 | t=arr.pop(s) 29 | new_arr.append(t) 30 | return new_arr 31 | 32 | list2=[2,34,56,23,43,555,86,45,777,1,333,44445,0,1,2] 33 | print(select_sort(list2)) 34 | 35 | 36 | list2.sort()##list已经pop删除清空 37 | print(list2) 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /graph algorithm/selectsort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Mon Jun 25 23:34:38 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 选择排序 10 | 11 | 每次遍历 只交换一次 12 | 13 | 共n-1次遍历 14 | 15 | O(N^2) 16 | 17 | 18 | """ 19 | 20 | def selectionSort(alist): 21 | for fillslot in range(len(alist)-1,0,-1): 22 | position_of_max = 0 23 | for location in range(1,fillslot+1): 24 | if alist[location] > alist[position_of_max]: 25 | ##确定最大值的位置 26 | position_of_max = location 27 | 28 | temp = alist[fillslot] 29 | ### 与最后的位置交换 30 | alist[fillslot] = alist[position_of_max] 31 | alist[position_of_max] = temp 32 | 33 | 34 | 35 | alist = [54,26,93,17,77,31,44,55,20] 36 | selectionSort(alist) 37 | print(alist) -------------------------------------------------------------------------------- /graph algorithm/sequentialSearch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Mon Jun 18 22:55:03 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 顺序查找 10 | 11 | 按照基本的顺序排序 12 | 13 | 14 | 从一项移动到 另一项 15 | 16 | 直到找到 正在寻找的项 17 | """ 18 | 19 | def sequentialSearch(list1,item): 20 | """ 21 | 22 | """ 23 | pos=0 24 | found = False 25 | 26 | 27 | while pos < len(list1) and not found : 28 | if list1[pos] == item: 29 | found = True 30 | 31 | else: 32 | pos += 1 33 | 34 | return found 35 | 36 | 37 | testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0] 38 | print(sequentialSearch(testlist, 3)) 39 | print(sequentialSearch(testlist, 13)) -------------------------------------------------------------------------------- /graph algorithm/seuqenSearch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Mon Jun 18 23:04:58 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 10 | 如果 列表排序 假设升序 11 | 12 | 进行搜索 13 | 14 | 15 | """ 16 | def orderedSequentialSearch(list2,item): 17 | 18 | 19 | pos = 0 20 | found = False 21 | stop = False 22 | 23 | 24 | while pos < len(list2) and not found and not stop : 25 | if list2[pos] == item: 26 | found = True 27 | 28 | elif list2[pos] > item: 29 | stop = True 30 | else: 31 | pos = pos+1 32 | 33 | return found 34 | 35 | 36 | 37 | testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42] 38 | print(orderedSequentialSearch(testlist, 3)) 39 | print(orderedSequentialSearch(testlist, 13)) -------------------------------------------------------------------------------- /graph algorithm/shellsort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Jun 26 16:35:09 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 希尔排序 10 | 11 | """ 12 | 13 | 14 | 15 | def shellSort(alist): 16 | ###分割成 多个等大的 子列 17 | sublist = len(alist)//2 18 | 19 | while sublist > 0: 20 | for startposition in range(sublist): 21 | gapInsertSort(alist,startposition,sublist) 22 | 23 | sublist = sublist // 2 ##增加 排序 子列len数 规模 24 | 25 | 26 | def gapInsertSort(alist,start,gap): 27 | ##间隔的插入排序 28 | for i in range(start+gap,len(alist),gap): 29 | current = alist[i] 30 | position = i 31 | 32 | while position >=gap and alist[position-gap] > current: 33 | ##左边的值较大 34 | alist[position] =alist[position-gap]###左边值先移到 现在的位置 35 | position = position - gap ###现在小的位置为 前一个位置 36 | 37 | alist[position] = current ##将刚刚的值 移动 38 | 39 | alist = [54,26,93,17,77,31,44,55,20] 40 | shellSort(alist) 41 | print(alist) -------------------------------------------------------------------------------- /graph algorithm/stack_binary_convert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 13 21:12:59 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 使用栈 进行十进制和二进制 之间的 转换 10 | 11 | 以及任意进制件的 转换 12 | 13 | 14 | """ 15 | from pythonds.basic.stack import Stack 16 | 17 | def dividedBy2(decnumber): 18 | """ 19 | 二进制构建数字序列 20 | 第一个余数是序列的最后一个数字 21 | """ 22 | remstack = Stack() 23 | 24 | while decnumber > 0 : 25 | rem = decnumber % 2 ### 余数 26 | remstack.push(rem) ### 存入栈底 27 | decnumber = decnumber // 2 28 | binString = "" 29 | while not remstack.isEmpty(): 30 | binString = binString + str(remstack.pop()) ## 调用栈 31 | 32 | return binString 33 | 34 | print(dividedBy2(134)) 35 | 36 | 37 | 38 | """ 39 | 除 2 更改为 除以 base 40 | 进行 任何基数的转换 41 | 42 | """ 43 | 44 | 45 | def dividedByBase(decnumber,base): 46 | """ 47 | 构建数字序列 48 | 第一个余数是序列的最后一个数字 49 | """ 50 | remstack = Stack() 51 | 52 | while decnumber > 0 : 53 | rem = decnumber % base ### 余数 54 | remstack.push(rem) ### 存入栈底 55 | decnumber = decnumber // base 56 | binString = "" 57 | while not remstack.isEmpty(): 58 | binString = binString + str(remstack.pop()) ## 调用栈 59 | 60 | return binString 61 | 62 | print(dividedByBase(134,10)) 63 | 64 | print(dividedByBase(134,16)) 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /graph algorithm/sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri May 18 11:57:06 2018 4 | 5 | @author: 刘闯 6 | sum: 7 | """ 8 | 9 | def my_sum(arr): 10 | if len(arr)==0: 11 | return 0 12 | elif len(arr)==1: 13 | return arr[0] 14 | else: 15 | arr.pop(0) 16 | return arr.pop(0)+sum(arr) 17 | list3=[1,5,4] 18 | print(my_sum(list3)) -------------------------------------------------------------------------------- /graph algorithm/sum2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri May 18 12:13:02 2018 4 | 5 | @author: 刘闯 6 | sum 7 | """ 8 | 9 | def my_sum(arr): 10 | if len(arr)==0: 11 | return 0 12 | elif len(arr)==1: 13 | return arr[0] 14 | else: 15 | t=arr.pop(0) ### 如果不引入变量t 将 再删除一次 16 | return t+sum(arr) 17 | list3=[4,5,3] 18 | print(my_sum(list3)) -------------------------------------------------------------------------------- /graph algorithm/unorderdedlist_node.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Jun 14 00:23:51 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 链表实现 无序列表 10 | 11 | 每一项 保留下一项的位置 12 | """ 13 | class Node: 14 | """ 15 | 链表的基本 是 节点 16 | 每个节点 包含列表项本身 以及下一个 节点的引用 17 | """ 18 | 19 | def __init__(self,initdata): 20 | self.data = initdata 21 | self.next = None 22 | 23 | def getData(self): 24 | return self.data 25 | 26 | 27 | def getNext(self): 28 | return self.next 29 | 30 | def setData(self,newdata): 31 | self.data = newdata 32 | 33 | def setNext(self,newnext): 34 | self.next = newnext 35 | 36 | 37 | 38 | 39 | class UnorderedList: 40 | """ 41 | 每个节点通过显式引用链接到下一个节点 42 | 第一个节点(包含第一个项) 43 | UnorderedList 类必须保持对第一个节点的引用 44 | """ 45 | 46 | 47 | def __init__(self): 48 | self.head = None 49 | 50 | 51 | def isEmpty(self): 52 | ###检查链表头是否是 None 的引用 53 | return self.head == None 54 | 55 | 56 | def add(self,item): 57 | temp = Node(item)## 创建一个新的结点 58 | temp.setNext(self.head) ###新结点 连在旧的第一个 59 | self.head = temp ### 头 引用 新的结点 60 | 61 | 62 | def size(self): 63 | current = self.head 64 | count = 0 65 | while current != None: 66 | count = count +1 67 | current = current.getNext() 68 | return count 69 | 70 | def search(self,item): 71 | current = self.head 72 | found = False 73 | while not found and current != None : 74 | #### 两个条件 : 有下一个值; 值 不是要寻找的 75 | if current.getData() == item: 76 | found = True 77 | else: 78 | current = current.getNext() 79 | return found 80 | 81 | 82 | def remove(self,item): 83 | current = self.head 84 | previous = None 85 | found = False 86 | 87 | while not found : 88 | ### 搜索 假设 删除项存在 89 | if current.getData() == item : 90 | found = True 91 | else: 92 | previous = current ###pre 在 current 前一个节点 93 | current = current.getNext() 94 | 95 | if previous == None : ### 删除项 为列表第一项 96 | self.head = current.getNext() 97 | else: 98 | previous.setNext(current.getNext()) 99 | 100 | 101 | 102 | mylist = UnorderedList() 103 | mylist.add(12) 104 | mylist.add(13) 105 | mylist.add(14) 106 | 107 | 108 | print(mylist.size()) 109 | print(mylist.search(12),mylist.search(15)) 110 | 111 | mylist.remove(13) 112 | print(mylist.search(13)) 113 | 114 | 115 | ### 链表类本身不包含任何节点对象。 116 | ###它只包含对链接结构中第一个节点的单个引用 -------------------------------------------------------------------------------- /graph algorithm/word_match.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat May 26 19:02:01 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | if word_a[i] == word_b[j]: 9 | # The letters match. 10 | cell[i][j] = cell[i-1][j-1] + 1 11 | else: 12 | # The letters don't match. 13 | cell[i][j] = max(cell[i-1][j], cell[i][j-1]) -------------------------------------------------------------------------------- /items/README.md: -------------------------------------------------------------------------------- 1 | # python 小项目练习 2 | 3 | # python 小程序 4 | 标签 :python 5 | 6 | # 1 Interweaving strings and removing digits 7 | > Your friend Rick is trying to send you a message, but he is concerned that it would get intercepted by his partner. He came up with a solution: 8 | > 1) Add digits in random places within the message. 9 | > 2) Split the resulting message in two. He wrote down every second character on one page, and the remaining ones on another. He then dispatched the two messages separately. 10 | Write a function interweave(s1, s2) that reverses this operation to decode his message! 11 | Example 1: interweave("hlo", "el") -> "hello" Example 2: interweave("h3lo", "el4") -> "hello" 12 | Rick's a bit peculiar about his formats. He would feel ashamed if he found out his message led to extra white spaces hanging around the edges of his message... 13 | 14 | * code 15 | 16 | ```python 17 | 18 | def interweave(s1,s2): 19 | s_1="" 20 | s_2="" 21 | out="" 22 | n=0 23 | for i in s1: 24 | if i not in '1234567890': 25 | t=''.join(i) 26 | s_1=s_1+t 27 | n1=len(s_1) 28 | for j in s2: 29 | if j not in '1234567890': 30 | p=''.join(j) 31 | s_2=s_2+p 32 | n2=len(s_2) 33 | #判断长度 但是 有待改进 : 如果位数差的比较多 while 34 | if n1==n2: 35 | pass 36 | elif n1 -1 and math.sqrt(n) % 1 == 0 86 | ``` 87 | ``` 88 | def is_square(n): 89 | i=1 90 | while n>0: 91 | n=n-i 92 | i=i+2 93 | #平方拆成等比数列 94 | return n==0 95 | ``` 96 | ------------ 97 | 98 | # 4 translate 字符转换 删除 99 | 100 | ```python 101 | intab = "aeiou" 102 | outtab = "12345" 103 | trantab = str.maketrans(intab, outtab) # 制作翻译表 104 | 105 | str = "this is string example....wow!!!" 106 | print (str.translate(trantab)) 107 | ``` 108 | 109 | ```python 110 | def disemvowel(string): 111 | return string.translate(None, 'aeiouAEIOU') 112 | ``` 113 | 114 | ------------ 115 | 116 | # 5 循环询问票价 117 | 118 | ```python 119 | 120 | """ 121 | #循环性 咨询票价 直到输入错误数据 可以选择继续 或者 quit 122 | 无线循环 123 | 输入quit 直接退出程序 124 | ###如何控制再开始一段循环 solved 125 | """ 126 | 127 | 128 | import time 129 | 130 | c=0 131 | while c< 10: 132 | b=True 133 | while b: 134 | d=input("Enter your age : ")#判断输入类型 135 | if d.isdigit(): #是不是全部是整数 136 | a=int(d) 137 | 138 | if a <=3 : 139 | print("It's free for you!") 140 | continue 141 | elif a>3 and a<12 : 142 | print("It costs 3$,please!") 143 | continue 144 | elif a>=12 and a< 100: 145 | print("It costs 6$, please!") 146 | continue 147 | else: 148 | b=False # 超出售票年龄范围 149 | c+=1 150 | print('\nError!!!(out of range). Wait for 5s') 151 | time.sleep(5) # 暂停5秒 152 | 153 | elif d!='quit': #输入有字符 不是quit 报错 继续运行 154 | print('\nError!!(Enter integer). Wait for 3s') 155 | time.sleep(3) 156 | break 157 | else: 158 | break 159 | 160 | if d=='quit': #输入quit 退出程序 161 | print("It is quiting") 162 | c=1002 163 | else: 164 | prompt="\nif you wnat to quit please enter quit:" 165 | prompt+="\nif you want to continue please enter any key: " 166 | e=input(prompt) 167 | if e =='quit': #输入有 quit 即时退出程序 168 | print("It is quiting") 169 | c=1001 170 | 171 | ``` 172 | 173 | 174 | -------- 175 | 176 | ## 6 Homework: A byte of python 177 | Checking whether a text is a palindrome should also ignore punctuation, spaces and case. For example, "Rise to vote, sir." is also a palindrome but our current program doesn't say it is. Can you improve the above program to recognize this palindrome? 178 | If you need a hint, the idea is that...1 179 | 180 | > Use a tuple (you can find a list of all punctuation marks here) to hold all the forbidden characters, then use the membership test to determine whether a character should be removed or not, i.e. forbidden = (!, ?, ., ...). 181 | 182 | 183 | -------- 184 | ## 7 心形图 185 | 186 | ```python 187 | grid=[['.','.','.','.','.','.','.'], 188 | ['.','*','*','.','.','.','.'], 189 | ['*','*','*','*','.','.','.'], 190 | ['*','*','*','*','*','.','.'], 191 | ['.','*','*','*','*','*','.'], 192 | ['*','*','*','*','*','.','.'], 193 | ['*','*','*','*','.','.','.'], 194 | ['.','*','*','.','.','.','.'], 195 | ['.','.','.','.','.','.','.']] 196 | i=0 197 | while i<7: 198 | for j in range(0,9): 199 | print(grid[j][i],end='') 200 | print('\n')##换行 201 | i+=1 202 | ``` 203 | 204 | 205 | -------- 206 | ## 8 tic tac toe 207 | [AI_tictactoe](http://inventwithpython.com/chapter10.html) 208 | 209 | ```python 210 | ###建立棋盘空格位置---棋子 现所有位置都是空格 211 | the_board={'1-1':' ','1-2':' ','1-3':' ', 212 | '2-1':' ','2-2':' ','2-3': '', 213 | '3-1':' ','3-2':' ','3-3':' ', 214 | } 215 | 216 | ###打印棋盘 217 | def print_board(board): 218 | ###参数为字典 219 | print(board['1-1']+'|'+board['1-2']+'|'+board['1-3']) 220 | print('-+-+-') 221 | print(board['2-1']+'|'+board['2-2']+'|'+board['2-3']) 222 | print('-+-+-') 223 | print(board['3-1']+'|'+board['3-2']+'|'+board['3-3']) 224 | 225 | 226 | ### 允许玩家修改棋子 227 | turn='X' 228 | for i in range(9): 229 | print_board(the_board) 230 | print('Turn for '+turn) 231 | move=input(" Move on which space?: ") 232 | the_board[move]=turn 233 | if turn == "X": 234 | turn='O' 235 | else: 236 | turn='X' 237 | 238 | print_board(the_board) 239 | ``` 240 | ------ 241 | 242 | ## 9 列表物品按数量添加到字典 243 | ```python 244 | 245 | ##展示 物品数目和分类 246 | def display_stuff(stu): 247 | for k , v in stu.items(): 248 | print(k + ': '+ str(v)) 249 | total_number=0 250 | total_number+=v 251 | print("\ntotal_number: " +str(total_number)) 252 | 253 | ### 添加物品----添加字典 254 | def add_stuff(st,add_stu): 255 | for i in add_stu: 256 | st.setdefault(i,0) ###防止字典里面不含该物品 257 | st[i]=st[i]+1 258 | return st ###注意函数需要返回值 259 | stuff={'rope':1,'arrow':3,'torch':4,'coin':32,'gold':12,'cloth':12} 260 | addstuff=['rope','rope','rope','gold','fish'] 261 | stuff_total=add_stuff(stuff,addstuff) 262 | display_stuff(stuff_total) 263 | ``` 264 | 265 | -------- 266 | 267 | ## 10 寻找文本中的 电话号码 email 268 | ```python 269 | # -*- coding: utf-8 -*- 270 | """ 271 | Created on Tue May 22 16:11:33 2018 272 | 273 | @author: 刘闯 274 | 275 | 提取 电话号码和 Email地址 276 | 277 | 278 | 1.从剪切板获取文本: 279 | 1-1pyperclip 280 | 2.找出其中的 电话号码 和Email 地址: 281 | 2-1 两个正则表达式 282 | 2-2 找出所有的匹配 283 | 2-3 放入字符串 284 | 2-4 如果没有匹配 ;;; 285 | 286 | 3. 粘贴到剪切板 287 | 288 | """ 289 | 290 | import pyperclip, re 291 | text=str(pyperclip.paste()) 292 | 293 | # phone 010-8888-8888 294 | phonenumber_regex=re.compile(r'''( 295 | (\d{4}|\(\d{4}\))? ##区号 0101 or (0101) 且不一定必须 296 | (\s|-|\.)? ##连接符 0101-1234 or 0101.1234 o1o1 1234 且不一定必须 297 | (\d{4}) 298 | (\s|-|\.)? 299 | (\d{4}) 300 | )''',re.VERBOSE) 301 | 302 | 303 | ## email ex: 1659608216@qq.com 304 | email_regex=re.compile(r'''( 305 | [a-zA-Z0-9._%+-]+ # username 306 | @ 307 | [a-zA-z0-9-]+ #domin name 308 | (\.[a-zA-Z]{2,})+ #.cn or.com (.edu.cn) 309 | )''',re.VERBOSE) 310 | 311 | ###findall 抓取信息 tuple--list 312 | matches=[] 313 | for groups in phonenumber_regex.findall(text): 314 | phonenumber='-'.join([groups[1],groups[3],groups[5]]) 315 | matches.append(phonenumber) 316 | for groups in email_regex.findall(text): 317 | matches.append(groups[0]) 318 | 319 | 320 | ####copy to clipboard 321 | if len(matches)>0: 322 | pyperclip.copy('\n'.join(matches)) 323 | print("Copied to clipboard:") 324 | print('\n'.join(matches)) 325 | else: 326 | print('No number or email found') 327 | 328 | ###问题 电话号码和 手机号码 冲突显示 需要个判断(开头) 329 | #### 校园邮箱 识别 缺失 solved 330 | #### 随机8位数字 都添加识别 错误 331 | 332 | #### 识别 3位 是数字还是电话号 333 | 334 | ###类似程序: 335 | 1. 寻找网站的URL https://开头 336 | 337 | 2. 寻找整理日期格式 338 | 339 | 3. 删除敏感信息 sub() 340 | 341 | 4. 寻找常见的英文打字错误 如:单词间多个空格 重复单词 多个标点符号 342 | 343 | ``` 344 | ------ 345 | 346 | ## 11 记录时间秒表 347 | 348 | ```python 349 | #!/usr/bin/env python3 350 | # -*- coding: utf-8 -*- 351 | """ 352 | Created on Sun Jul 15 00:53:43 2018 353 | @author: liuchuang 354 | 超级秒表 项目 355 | 1.记录从按下回车键开始,每次按键的时间,每次按键都是一个新的“单圈”。 356 | 2.打印圈数、总时间和单圈时间。 357 | 这意味着代码将需要完成以下任务: 358 | 1.在程序开始时,通过调用 time.time()得到当前时间,将它保存为一个时间戳。 在每个单圈开始时也一样。 359 | 2.记录圈数,每次用户按下回车键时加 1。 用时间戳相减,得到计算流逝的时间。 360 | 3.处理 KeyboardInterrupt 异常,这样用户可以按 Ctrl-C 退出。 361 | 4.打开一个新的文件编辑器窗口,并保存为 stopwatch.py。 362 | 创建一个简单的工时表应用程序,当输入一个人的名字时,用当前的时间记录 下他们进入或离开的时间 363 | """ 364 | 365 | import time 366 | 367 | 368 | # Display the program's instructions. 369 | print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.') 370 | 371 | input() 372 | print("Start!") 373 | 374 | startTime = time.time() 375 | lastTime = startTime 376 | lapNum =1 377 | 378 | 379 | try: 380 | while True: 381 | input() 382 | lapTime =round(time.time()- lastTime,4) 383 | totalTime = round(time.time()-startTime,4) 384 | print("Lap %s : total time : %s lap time: %s" %(lapNum,totalTime,lapTime),end="") 385 | lapNum+=1 386 | lastTime = time.time() 387 | 388 | except KeyboardInterrupt: 389 | print("\n done") 390 | ``` 391 | 392 | -------- 393 | 394 | 395 | 396 | 397 | 398 | -------------------------------------------------------------------------------- /items/changeInto9parts_pillow_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Jul 5 23:28:05 2018 5 | 6 | @author: liuchuang 7 | """ 8 | 9 | 10 | from PIL import Image 11 | ## pyhton pillow bag 12 | 13 | 14 | def fillImage(image): 15 | """ 16 | if picture is not square 17 | filled with white (or some other color) 18 | """ 19 | width, height = image.size 20 | length = max(width,height) 21 | 22 | new_image = Image.new(image.mode,(length,length),color='white') 23 | 24 | 25 | if width > height : 26 | new_image.paste(image,(0,int((length-height)/2))) 27 | 28 | else: 29 | new_image.paste(image,(int((length-width)/2),0)) 30 | return new_image 31 | 32 | 33 | def cutImage(image): 34 | """ 35 | cut into 9 parts 3X3 36 | """ 37 | width, height = image.size 38 | 39 | part_width = int(width/3) 40 | part_height = int(height/3) 41 | 42 | box_list = [] ### to store 9 parts 43 | 44 | for i in range(3): 45 | for j in range(3): 46 | 47 | box = (j * part_width, i * part_width, (j + 1) * part_width, (i + 1) * part_width) 48 | box_list.append(box) 49 | 50 | image_list = [image.crop(box) for box in box_list] ## save 9 parts of images 51 | 52 | return image_list 53 | 54 | 55 | 56 | def saveImage(image_list,out_dir): 57 | for (index, image) in enumerate(image_list, start=1): 58 | # enumerate 59 | image.save("{out_dir}_{index}.png".format(out_dir=out_dir, index=index), "PNG") 60 | 61 | 62 | 63 | def changeToNineParts(file_path,out_dir='./'): 64 | image = Image.open(file_path) 65 | image1 = fillImage(image) 66 | image_list = cutImage(image1) 67 | pic_name = file_path.split('.')[0] 68 | out_dir = out_dir+ r'/'+pic_name 69 | saveImage(image_list, out_dir) 70 | 71 | 72 | if __name__ == '__main__': 73 | changeToNineParts('ttt.png') 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /items/changeToChar_pil_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sat Jul 7 00:19:21 2018 5 | 6 | @author: liuchuang 7 | 8 | 参考 https://www.shiyanlou.com/courses/370/labs/1191/document 9 | 10 | 目前 只能转换背景为白色的图片 11 | 12 | """ 13 | 14 | from PIL import Image 15 | 16 | def get_char(r,g,b,alpha=256): 17 | """ 18 | change rgb to char 19 | gray / 256 = x / len(ascii_char) 20 | """ 21 | if alpha == 0: 22 | return " " 23 | ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ") 24 | 25 | gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) 26 | 27 | x= int((gray/(256.0+1))*len(ascii_char)) 28 | 29 | return ascii_char[x] 30 | 31 | 32 | def write_file(out_filename,cont): 33 | """ 34 | write as a txt 35 | """ 36 | 37 | with open(out_filename,'w') as fil: 38 | fil.write(cont) 39 | 40 | 41 | def change_to_char(filename,width=150,height=150,out_filename="out_file"): 42 | """ 43 | change 44 | print 45 | write 46 | """ 47 | text = "" 48 | 49 | im = Image.open(filename) 50 | im = im.resize((width,height),Image.NEAREST) 51 | 52 | for i in range(height): 53 | for j in range(width): 54 | text += get_char(*im.getpixel((j,i))) ## get pixel every place 55 | 56 | text +='\n' ## change line 57 | print(text) 58 | write_file(out_filename,text) 59 | 60 | if __name__ == '__main__' : 61 | change_to_char('lll.JPG') 62 | -------------------------------------------------------------------------------- /items/character_graph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri May 18 21:31:11 2018 4 | 5 | @author: 刘闯 6 | 7 | 字符图网格 8 | 打印心形 9 | """ 10 | 11 | grid=[['.','.','.','.','.','.','.'], 12 | ['.','*','*','.','.','.','.'], 13 | ['*','*','*','*','.','.','.'], 14 | ['*','*','*','*','*','.','.'], 15 | ['.','*','*','*','*','*','.'], 16 | ['*','*','*','*','*','.','.'], 17 | ['*','*','*','*','.','.','.'], 18 | ['.','*','*','.','.','.','.'], 19 | ['.','.','.','.','.','.','.']] 20 | i=0 21 | while i<7: 22 | for j in range(0,9): 23 | print(grid[j][i],end='') 24 | print('\n') 25 | i+=1 -------------------------------------------------------------------------------- /items/copy_paste.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun May 20 22:38:22 2018 4 | 5 | @author: 刘闯 6 | 7 | 修改剪切板内容 重新粘贴 8 | 9 | 10 | """ 11 | 12 | import pyperclip 13 | 14 | text= pyperclip.paste() 15 | #返回剪切板上的所有文本 返回一个 长的字符串 16 | print(text+'#') 17 | 18 | #切割字符串 以/n W为标志 得到列表 19 | lines=text.split('\n') 20 | for i in range(len(lines)): 21 | lines[i]='* '+lines[i] 22 | text='\n'.join(lines) 23 | pyperclip.copy(text) #改变剪切板内容 24 | print(text) -------------------------------------------------------------------------------- /items/find_text.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon May 21 23:54:58 2018 4 | 5 | @author: 刘闯 6 | 7 | 文本模式查找 8 | 9 | """ 10 | ###查找一个12位的电话号码 例: 123-456-7890 11 | def is_phonenumber(text): 12 | # 逐位判断 13 | if len(text)!=12: 14 | return False 15 | for i in range(0,3): 16 | if not text[i].isdecimal(): 17 | return False 18 | if text[3] != '-': 19 | return False 20 | for i in range(4,7): 21 | if not text[i].isdecimal(): 22 | return False 23 | if text[7] != '-': 24 | return False 25 | for i in range(8,12): 26 | if not text[i].isdecimal(): 27 | return False 28 | return True 29 | 30 | print(is_phonenumber('123-456-7890')) 31 | print(is_phonenumber('123-456-789u')) 32 | 33 | ###########在多于12位的文本中查找 34 | def find_text(message): 35 | for i in range(len(message)): 36 | message_temporary=message[i:i+12] 37 | if is_phonenumber(message_temporary): 38 | print("phone number: " + message_temporary) 39 | print('Done') 40 | 41 | ########只能查找固定模式的文本 42 | ###代码运行较慢 O(n) 43 | 44 | 45 | 46 | 47 | 48 | m='123-456-7890 for a ment aline libe lieb 098-654-3222 for a moment 1234-123-123' 49 | find_text(m) 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /items/findmaxmanmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Apr 25 22:16:28 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | def findmaxandmin(L): 9 | if L==[]: 10 | return(None,None) 11 | else: 12 | min=L[0] 13 | max=L[0] 14 | for i in L: 15 | if imax: 18 | max=i 19 | return(min,max) 20 | 21 | print(findmaxandmin([])) 22 | -------------------------------------------------------------------------------- /items/intersection_leecode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Jun 5 11:13:11 2018 5 | 6 | @author: liuchuang 7 | 8 | 给定两个数组,写一个函数来计算它们的交集。 9 | """ 10 | 11 | 12 | """ 13 | class Solution: 14 | def intersection(self, nums1, nums2): 15 | """ 16 | :type nums1: List[int] 17 | :type nums2: List[int] 18 | :rtype: List[int] 19 | """ 20 | a = set() 21 | b = set() 22 | for i in nums1: 23 | a.add(i) 24 | for j in nums2: 25 | b.add(j) 26 | c = a&b 27 | return list(c) 28 | """ 29 | 30 | 31 | class Solution: 32 | def intersection(self, nums1, nums2): 33 | """ 34 | :type nums1: List[int] 35 | :type nums2: List[int] 36 | :rtype: List[int] 37 | """ 38 | nums=[] 39 | for i in nums1: 40 | if i in nums2 and i not in nums: 41 | nums.append(i) 42 | return nums 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /items/michelson_lightpipes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Fri Jun 29 16:10:35 2018 5 | 6 | @author: liuchuang 7 | 8 | 改变角度 9 | """ 10 | 11 | from LightPipes import * 12 | import matplotlib.pyplot as plt 13 | import matplotlib.image as mpimg 14 | import numpy as np 15 | 16 | wavelength=1040*nm #wavelength of HeNe laser 17 | size=10*mm # size of the grid 18 | N=800 # number (NxN) of grid pixels 19 | R=3*mm # laser beam radius 20 | z1=8*cm # length of arm 1 21 | z2=8*cm # length of arm 2 22 | z3=1*cm # distance laser to beamsplitter 23 | z4=5*cm # distance beamsplitter to screen 24 | Rbs=0.3 # 分光镜反射 37 55 影响不大 25 | ty=0.0*mrad # tilt of mirror 1 26 | f=50*cm # focal length of positive lens 27 | 28 | """ 29 | ###读取 迈克尔逊干涉图片 30 | img=mpimg.imread('Michelson.png') 31 | plt.imshow(img); plt.axis('off') 32 | plt.show() 33 | """ 34 | 35 | for i in range(10): 36 | tx=(i-1)/10*mrad 37 | #Generate a weak converging laser beam using a weak positive lens: 38 | F=Begin(size,wavelength,N) 39 | F=GaussHermite(0,0,1,R,F) 40 | F=Lens(f,0,0,F) 41 | 42 | #Propagate to the beamsplitter: 43 | F=Forvard(z3,F) 44 | 45 | #Split the beam and propagate to mirror #2: 46 | F2=IntAttenuator(1-Rbs,F) 47 | F2=Forvard(z2,F2) 48 | 49 | #Introduce tilt and propagate back to the beamsplitter: 50 | F2=Tilt(tx,ty,F2) 51 | F2=Forvard(z2,F2) 52 | F2=IntAttenuator(Rbs,F2) 53 | 54 | #Split off the second beam and propagate to- and back from the mirror #1: 55 | F10=IntAttenuator(Rbs,F) 56 | F1=Forvard(z1*2,F10) 57 | F1=IntAttenuator(1-Rbs,F1) 58 | 59 | #Recombine the two beams and propagate to the screen: 60 | F=BeamMix(F1,F2) 61 | F=Forvard(z4,F) 62 | I=Intensity(1,F) 63 | 64 | plt.subplot(2,5,i+1) 65 | 66 | plt.imshow(I,cmap='jet'); plt.axis('off'); 67 | plt.show() 68 | -------------------------------------------------------------------------------- /items/password.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun May 20 19:30:38 2018 4 | 5 | @author: 刘闯 6 | 7 | 口令保管箱 8 | """ 9 | 10 | ###账号的名称和密码 11 | passwords={'Email':'asdfghjkl1234', 12 | 'QQ':'1234567899asdfgh', 13 | 'Wechat':'3ertyhvgjihhh'} 14 | 15 | 16 | ##处理命令行参数 17 | ##命令行参数储存在sys.argv 18 | 19 | import sys ##命令行参数 20 | import pyperclip 21 | 22 | 23 | if len(sys.argv)<2: 24 | print('Usage: python pw.py [acount] - copy account password') 25 | sys.exit() 26 | account=sys.argv[1] 27 | ###第一个命令行参数是账户名称 28 | 29 | ####复制正确的口令 30 | if account in passwords.keys(): 31 | pyperclip.copy(passwords[account]) 32 | print('password for ' + account + ' copied to clipboard.') 33 | else: 34 | print("There is no account named " + account ) 35 | -------------------------------------------------------------------------------- /items/prc_list.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun May 13 01:11:09 2018 4 | 5 | @author: dell 6 | """ 7 | list=['L','C','Z','X','W'] 8 | print(list) 9 | print("w is not intended") 10 | list.remove('W') #移除一个嘉宾 11 | list.append('w') #增补一个嘉宾 12 | print(list) 13 | 14 | #修改名单 15 | list.insert(0,'chuang') 16 | n=len(list) 17 | if n%2==1: 18 | list.insert((n-1/2),'xiao') 19 | else: 20 | list.insert(int((n/2)),'xiao') 21 | list.append('wei') 22 | print(list) 23 | 24 | #每一位嘉宾发出邀请 25 | for i in list: 26 | print("invite "+ i.title() + ' to my party')#每一位嘉宾发出邀请 27 | print('\nSorry,only two people i can invite') 28 | 29 | 30 | #删除只剩两位 31 | n=len(list) 32 | while n >2: 33 | l=list.pop() 34 | print(l + " I am sorry")##如果不用L替换 list.pop会再删除一个 隔着删除 35 | n=len(list) 36 | print(list) 37 | for i in list: 38 | print("invite "+ i.title() + ' to my party')#剩下两位嘉宾发出邀请 39 | 40 | #清空名单 41 | del list[::] 42 | if len(list)==0: 43 | print('名单清空') 44 | else: 45 | print("no") 46 | -------------------------------------------------------------------------------- /items/random_test_paper_item.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu May 31 16:48:09 2018 4 | 5 | @author: 刘闯 6 | 7 | 8 | 生成随机的测试文件:省份 和省会城市 9 | 10 | 1.创建 30 份试卷 11 | 2.每份试卷 20 个选择题 顺序随机 12 | 3.每个问题 一个正确答案 3个随机错误答案 13 | 4.测验试卷 写入 30个文本文件 14 | 5.答案 写入30个文本文件 15 | 16 | """ 17 | 18 | import random ## 随机安排问题和答案 导入 random 19 | 20 | ###1 测验数据保存在一个字典中 21 | 22 | #### keys: 省份 ; values: 省会; 23 | Capitals={"Hei Longjiang": "Ha'erbin", 24 | "Jilin" :"Changchun", 25 | "Liaoning":"Shenyang", 26 | "Hebei":"Shijiazhuang", 27 | "Henan":"Zhengzhou", 28 | "Anhui":"Hefei", 29 | "Hubei":"Wuhan", 30 | "Hunan":"Changsha", 31 | "Shanxi_1":"Xi'an", ###如何解决字典里 储存相同字符问题 32 | "Shanxi_3":"Datong", 33 | "Gansu":"Lanzhou", 34 | "Ningxia":"Yinchuan", 35 | "Hainan":"Haikou", 36 | "Fujian":"Fuzhou", 37 | "Jiangxi":"Taiyuan", 38 | "jiangsu":"Nanjing", 39 | "Zhejiang":"Hanzhou", 40 | "Sichuan":"Chengdu", 41 | "Shandong":"Jinan", 42 | "Guangdong":"Guangzzhou" 43 | } 44 | 45 | ###2 创建30份问卷 并随机给出候选答案 46 | 47 | ### 创建 quiz 和 answer 文件 48 | for quiz_num in range(30): 49 | quizFile=open('Capitals_quiz%s.txt'%(quiz_num+1),'w') 50 | answerFile=open('Capital_quiz_answer%s.txt'%(quiz_num+1),'w') 51 | 52 | ###创建测验标题 53 | quizFile.write("Name:\n\nDate:\n\nPeriod:\n\n") 54 | quizFile.write((' '* 20)+ 'State Captial Quiz (Form %s)'%(quiz_num+1)) 55 | quizFile.write('\n\n') 56 | answerFile.write('Quiz answer') 57 | answerFile.write('\n\n') 58 | 59 | 60 | ###创建省份的随机列表 61 | states=list(Capitals.keys()) 62 | random.shuffle(states) 63 | 64 | ### 3 创建答案选 65 | for question_num in range(20): 66 | correct_answer= Capitals[states[question_num]] 67 | wrong_answer=list(Capitals.values()) 68 | del wrong_answer[wrong_answer.index(correct_answer)] 69 | wrong_answer=random.sample(wrong_answer,3)###选择的列表 ,随机选择的 70 | answer_options=wrong_answer+[correct_answer] 71 | random.shuffle(answer_options) 72 | 73 | ###4 将内容写进测试试卷 和答案文件 74 | #### 写入问题 和答案选项 75 | quizFile.write('%s.What is the capital of %s?\n' %(question_num+1,states[question_num])) 76 | for i in range(4): 77 | quizFile.write(' %s.%s\n'%('ABCD'[i],answer_options[i])) 78 | quizFile.write('\n') 79 | 80 | #### 写入答案 list.index!!! 81 | 82 | answerFile.write('%s.%s\n'%(question_num+1,'ABCD'[answer_options.index(correct_answer)])) 83 | quizFile.close() 84 | answerFile.close() 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /items/read_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Apr 20 14:54:30 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | poem = ''' 9 | 10 | 11 | Programming is fun 12 | When the work is done 13 | if you wanna make your work also fun: 14 | use Python! 15 | ''' 16 | 17 | f=open('poem.text','w') 18 | f.write(poem) 19 | f.close 20 | 21 | f=open('poem.text','r') 22 | while True: 23 | line=f.readline() 24 | if len(line)==0: 25 | break 26 | print(line,end=" ") 27 | 28 | f.close 29 | 30 | -------------------------------------------------------------------------------- /items/regex_find_emial_phonenumber.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue May 22 16:11:33 2018 4 | 5 | @author: 刘闯 6 | 7 | 提取 电话号码和 Email地址 8 | 9 | 10 | 1.从剪切板获取文本: 11 | 1-1pyperclip 12 | 2.找出其中的 电话号码 和Email 地址: 13 | 2-1 两个正则表达式 14 | 2-2 找出所有的匹配 15 | 2-3 放入字符串 16 | 2-4 如果没有匹配 ;;; 17 | 18 | 3. 粘贴到剪切板 19 | 20 | """ 21 | 22 | import pyperclip, re 23 | text=str(pyperclip.paste()) 24 | 25 | # phone 010-8888-8888 26 | phonenumber_regex=re.compile(r'''( 27 | (\d{4}|\(\d{4}\))? ##区号 0101 or (0110) 且不一定必须 28 | (\s|-|\.)? ##连接符 0101-1234 or 0101.1234 0101 1234 且不一定必须 29 | (\d{4}) 30 | (\s|-|\.)? 31 | (\d{4}) 32 | )''',re.VERBOSE) 33 | 34 | 35 | ## email ex: 1659608216@qq.com 36 | email_regex=re.compile(r'''( 37 | [a-zA-Z0-9._%+-]+ # username 38 | @ 39 | [a-zA-z0-9-]+ #domin name 40 | (\.[a-zA-Z]{2,})+ #.cn or.com (.edu.cn) 41 | )''',re.VERBOSE) 42 | 43 | ###findall 抓取信息 tuple--list 44 | matches=[] 45 | for groups in phonenumber_regex.findall(text): 46 | phonenumber='-'.join([groups[1],groups[3],groups[5]]) 47 | matches.append(phonenumber) 48 | for groups in email_regex.findall(text): 49 | matches.append(groups[0]) 50 | 51 | 52 | ####copy to clipboard 53 | if len(matches)>0: 54 | pyperclip.copy('\n'.join(matches)) 55 | print("Copied to clipboard:") 56 | print('\n'.join(matches)) 57 | else: 58 | print('No number or email found') 59 | 60 | ###问题 电话号码和 手机号码 冲突显示 需要个判断(开头) 61 | #### 校园邮箱 识别 缺失 solved 62 | #### 随机8位数字 都添加识别 错误 63 | 64 | #### 识别 3位 是数字还是电话号 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /items/stopwatch_time_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sun Jul 15 00:53:43 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 超级秒表 项目 10 | 11 | 1.记录从按下回车键开始,每次按键的时间,每次按键都是一个新的“单圈”。 12 | 2.打印圈数、总时间和单圈时间。 13 | 14 | 15 | 这意味着代码将需要完成以下任务: 16 | 1.在程序开始时,通过调用 time.time()得到当前时间,将它保存为一个时间戳。 在每个单圈开始时也一样。 17 | 2.记录圈数,每次用户按下回车键时加 1。 用时间戳相减,得到计算流逝的时间。 18 | 3.处理 KeyboardInterrupt 异常,这样用户可以按 Ctrl-C 退出。 19 | 4.打开一个新的文件编辑器窗口,并保存为 stopwatch.py。 20 | 21 | 22 | 23 | 24 | 创建一个简单的工时表应用程序,当输入一个人的名字时,用当前的时间记录 下他们进入或离开的时间 25 | 26 | 27 | 28 | 29 | """ 30 | 31 | import time 32 | 33 | 34 | # Display the program's instructions. 35 | print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.') 36 | 37 | input() 38 | print("Start!") 39 | 40 | startTime = time.time() 41 | lastTime = startTime 42 | lapNum =1 43 | 44 | 45 | try: 46 | while True: 47 | input() 48 | lapTime =round(time.time()- lastTime,4) 49 | totalTime = round(time.time()-startTime,4) 50 | print("Lap %s : total time : %s lap time: %s" %(lapNum,totalTime,lapTime),end="") 51 | lapNum+=1 52 | lastTime = time.time() 53 | 54 | except KeyboardInterrupt: 55 | print("\n done") 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /items/tictactoe_model.py: -------------------------------------------------------------------------------- 1 | ta# -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri May 18 23:36:31 2018 4 | 5 | @author:刘闯 6 | 7 | 利用数据结构 建立模型 8 | 9 | 井字棋 10 | """ 11 | 12 | 13 | ###建立棋盘空格位置---棋子 现所有位置都是空格 14 | the_board={'1-1':' ','1-2':' ','1-3':' ', 15 | '2-1':' ','2-2':' ','2-3': '', 16 | '3-1':' ','3-2':' ','3-3':' ', 17 | } 18 | 19 | ###打印棋盘 20 | def print_board(board): 21 | ###参数为字典 22 | print(board['1-1']+'|'+board['1-2']+'|'+board['1-3']) 23 | print('-+-+-') 24 | print(board['2-1']+'|'+board['2-2']+'|'+board['2-3']) 25 | print('-+-+-') 26 | print(board['3-1']+'|'+board['3-2']+'|'+board['3-3']) 27 | 28 | 29 | ### 允许玩家修改棋子 30 | turn='X' 31 | for i in range(9): 32 | print_board(the_board) 33 | print('Turn for '+turn) 34 | move=input(" Move on which space?: ") 35 | the_board[move]=turn 36 | if turn == "X": 37 | turn='O' 38 | else: 39 | turn='X' 40 | 41 | print_board(the_board) 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /items/while_75.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon May 14 00:15:01 2018 4 | 5 | @author: dell 6 | 7 | 8 | 9 | #循环性 咨询票价 直到输入错误数据 可以选择继续 或者 quit 10 | 无线循环 11 | 输入quit 直接退出程序 12 | ###如何控制再开始一段循环 solved 13 | """ 14 | 15 | 16 | import time 17 | 18 | c=0 19 | while c< 10: 20 | b=True 21 | while b: 22 | d=input("Enter your age : ")#判断输入类型 23 | if d.isdigit(): #是不是全部是整数 24 | a=int(d) 25 | 26 | if a <=3 : 27 | print("It's free for you!") 28 | continue 29 | elif a>3 and a<12 : 30 | print("It costs 3$,please!") 31 | continue 32 | elif a>=12 and a< 100: 33 | print("It costs 6$, please!") 34 | continue 35 | else: 36 | b=False # 超出售票年龄范围 37 | c+=1 38 | print('\nError!!!(out of range). Wait for 5s') 39 | time.sleep(5) # 暂停5秒 40 | 41 | elif d!='quit': #输入有字符 不是quit 报错 继续运行 42 | print('\nError!!(Enter integer). Wait for 3s') 43 | time.sleep(3) 44 | break 45 | else: 46 | break 47 | 48 | if d=='quit': #输入quit 退出程序 49 | print("It is quiting") 50 | c=1002 51 | else: 52 | prompt="\nif you wnat to quit please enter quit:" 53 | prompt+="\nif you want to continue please enter any key: " 54 | e=input(prompt) 55 | if e =='quit': #输入有 quit 即时退出程序 56 | print("It is quiting") 57 | c=1001 58 | 59 | ''' 60 | 该程序有操作次数限制 61 | 如何控制无限次 solved 62 | ''' 63 | -------------------------------------------------------------------------------- /items/word_match.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat May 26 19:02:01 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | if word_a[i] == word_b[j]: 9 | # The letters match. 10 | cell[i][j] = cell[i-1][j-1] + 1 11 | else: 12 | # The letters don't match. 13 | cell[i][j] = max(cell[i-1][j], cell[i][j-1]) -------------------------------------------------------------------------------- /python_ProcessFile/README.md: -------------------------------------------------------------------------------- 1 | # 文件处理 2 | 3 | ## 1 读写文件 4 | 5 | ### 1 读取文件 6 | 7 | #### 1 文件路径 8 | > 1 文件在程序文件目录 或者目录下的文件夹 9 | 使用相对路径打开文件 10 | > 2 文件在其他文件夹 提供绝对路径 11 | 'c:\Users\ehmatthes\other_files' 12 | 13 | #### 2 read 14 | .read():读取文件内容 储存字符串在变量中 15 | .readlines(): 读取每一行,储存在列表里 16 | 储存在别的变量下 可在with调用文件语句外 使用 17 | 18 | #### 3 with 19 | ```python 20 | with open(filename,'w') as file_object: 21 | 22 | 首先执行open('output', 'w'),返回一个文件对象; 23 | 调用这个文件对象的__enter__方法,并将__enter__方法的返回值赋值给变量f; 24 | 执行with语句体,即with语句包裹起来的代码块; 25 | 不管执行过程中是否发生了异常,执行文件对象的__exit__方法,在__exit__方法中关闭文件。 26 | 这里的关键在于open返回的文件对象实现了__enter__和__exit__方法。一个实现了__enter__和__exit__方法的对象就称之为上下文管理器。 27 | 28 | ``` 29 | 30 | ###2 写入文件 31 | > 只能将字符串写入文本,数值数据需先转换 str() 32 | 33 | 34 | ### 4 创建文件夹 35 | ```python 36 | import os 37 | os.makedirs('C:\\Liu\\Chuang\\o') 38 | ###创建多层文件夹 39 | ``` 40 | 41 | ### 5 os.path 模块 : 文件名和文件路径 42 | 43 | #### 1 绝对路径 和相对路径 44 | ```python 45 | os.path.abspath('.') ##'.'对应着当前路径 46 | os.path.isabs()# 判断是否为绝对路径 47 | os.path.basename('')## 文件名 48 | os.path.dirname('')## 文件路径名 49 | os.path.split('')## t同时获得 文件名和路径的元组 的 50 | ``` 51 | 52 | #### 2 查看文件和文件夹 内容 53 | ```python 54 | os.path.getsize('') ###返回文件的字节数 55 | os.listdir('')## 返回路径下的所有文件 56 | ###利用个循环 可以计算 路径下所有文件 总字节数 57 | ``` 58 | 59 | #### 3 检查路径的有效性 60 | ```python 61 | os.path.exists() ### 检测路径是否存在 62 | os.path.isdir('')###path 存在 并且是一个文件夹 63 | os.path.isfile('') ### path 存在 并且是一个文件 64 | ``` 65 | 66 | 67 | 68 | ### 6 用 shelve 模块 保存变量 (二进制文件) 69 | ```python 70 | import shelve 71 | shelfFile= shelve.open('mydata') 72 | Men=['Liu','Chuang','chuang'] 73 | ## 类似于字典 有keys 有values 74 | shelfFile['man']=Men 75 | shelfFile.close() 76 | ``` 77 | 78 | 79 | ### 7 pprint.pformat() 函数保存变量 创建py 文件 80 | ```python 81 | import pprint 82 | cats=[{'name':'Liu','Age':'16'},{'name':'Chuang','age':'12'}] 83 | fileCat=open('mycat.py','w') 84 | fileCat.write('cats =' + pprint.pformat(cats) + '\n')## pprint 返回字符串 85 | fileCat.close() 86 | 87 | #导入python 脚本 88 | import mycat 89 | mycat.cats 90 | mycat.cats[0] 91 | ### 只有基本数据类型 整形 浮点型 字符串 列表 字典 作为简单文本写入 92 | ``` 93 | 94 | 95 | ## 2 组织文件 96 | ### 1 shutil 模块 97 | 98 | #### 1 复制文件和文件夹 99 | ```python 100 | import os,shutil 101 | 102 | os.chdir('C:\\') ## 更爱当前目录 103 | shutil.copy('sourse','destination') #!!! 返回一个字符串 被复制文件的路径 104 | ### 如果 destination 是一个文件名 ,复制文件的新名字 否则 原名 105 | 106 | shutil.copytree("c:\\a","c:\\a_backup") ###复制整个文件夹 以及他包括的文件以及文件夹 107 | ### 相当于备份 a 108 | ``` 109 | 110 | #### 2 文件和文件夹的移动 111 | ```python 112 | shutil.move('sourse','destination') 113 | ``` 114 | * 1 des为文件夹 则文件 移入文件夹 保存原有的文件名 !!! 很可能和源文件冲突覆盖 115 | * 2 des 为文件名 则将文件移动到文件夹并且 更改名字 116 | ```python 117 | shutil.move("C:\\bacon.txt","C:\\eggs\\new_bacon.txt") 118 | ``` 119 | 120 | * 3 如果目录下没有文件夹 所以假定des指定的是一个文件而不是文件夹, 121 | ```python 122 | bacon.txt ##文本文件改名为 eggs 无扩展名 123 | ``` 124 | 125 | #### 3 永久删除文件和文件夹 126 | ```python 127 | os.unlink(path)## 删除路径的文件 128 | os.rmdir(path)## 删除路径的空文件夹 129 | os.rmtree(path) ## 删除文件夹以及其包含的所有文件和文件夹 130 | ``` 131 | 132 | #### 4 文件删除到 回收站 : send2trash 133 | ```python 134 | import send2trash 135 | send2trash.send2trash("") 136 | ``` 137 | 138 | ### 2 遍历目录树: 处理文件夹中的每一个文件 139 | ```python 140 | import os 141 | for folderName,subfolders,filenames in os.walk("C:\\"): 142 | print(folderName) 143 | os.walk()###返回三个值 1 当前文件夹的字符串 2 当前文件夹的子文件夹 字符串列表 3 当前文件夹的文件字符串列表 144 | ``` 145 | 146 | ### 3 zipfile模块 压缩 文件 147 | #### 1 读取 ZIP文件 148 | ```python 149 | import zipfile ,os 150 | os.chdir(r'C:\Users\dell\Desktop\summer_camp\LAMDA') 151 | liuzip=zipfile.ZipFile('Liu.zip') 152 | names=liuzip.namelist() 153 | for name in names: 154 | print(name.decode('utf-8'))###?如何打印中文 待解决 155 | 156 | LiuInfo=liuzip.getinfo('spam.txt') 157 | LiuInfo.file_size 158 | LiuInfo.compress_size 159 | 160 | """ 161 | import os 162 | 163 | inpath = 'G:\Android\MyAndroid\UI设计' 164 | uipath = unicode(inpath,"utf-8") ##对路径进行utf-8编码 165 | 166 | list = os.listdir(uipath) ##获得文件目录列表 167 | 168 | for each in list: ##遍历list列表 169 | print(each.encode('utf-8')) ##将该目录下文件名全部打印出来 170 | 171 | import codecs 172 | f = codecs.open('text.text','r+',encoding='utf-8')#必须事先知道文件的编码格式,这里文件编码是使用的utf-8 173 | content = f.read()#如果open时使用的encoding和文件本身的encoding不一致的话,那么这里将将会产生错误 174 | f.write('你想要写入的信息') 175 | f.close() 176 | 177 | import chardet 178 | # 获取文件编码类型 179 | def get_encoding(file): 180 | # 二进制方式读取,获取字节数据,检测类型 181 | with open(file, 'rb') as f: 182 | return chardet.detect(f.read())['encoding'] 183 | 184 | file_name = 'my.ini' 185 | encoding = get_encoding(file_name) 186 | print(encoding) 187 | """ 188 | ``` 189 | 190 | #### 2 从zip中解压缩 191 | ```python 192 | liuzip.extractall('A') # 全部解压 可以传入一个文件夹名称 解压缩到 文件夹目录 193 | liuzip.extract('B.txt',A)## 单个解压到指定目录 194 | ``` 195 | 196 | #### 3 创建压缩文件 197 | ```python 198 | import zipfile 199 | new_zip=zipfile.ZipFile('new.zip','w') 200 | new_zip.write('spam.txt',compress_type=zipfile.ZIP_DEALATED) 201 | ##'w'写入会擦除原有内容 ‘a’添加 202 | new_zip.close() 203 | ``` 204 | -------------------------------------------------------------------------------- /python_fundamental/README.md: -------------------------------------------------------------------------------- 1 | 2 | # python 基础学习 3 | 4 | 5 | 6 | 7 | # 0 基本 8 | * [Python·内置函数](https://docs.python.org/3/library/functions.html) 9 | * [Python.模块](https://pymotw.com/3/) 10 | * [python.代码格式](https://www.python.org/dev/peps/pep-0008/) 11 | 12 | > The Software Development Process 13 | * What (Analysis) 14 | * How (Design) 15 | * Do It (Implementation) 16 | * Test (Testing and Debugging) 17 | * Use (Operation or Deployment) 18 | * Maintain (Refinement) 19 | 20 | [what is the next.](https://python.swaroopch.com/what_next.html) 21 | 22 | ### 静态语言 vs 动态语言(待解决) 23 | * 对于静态语言(例如Java)来说,如果需要传入Animal类型,则传入的对象必须是Animal类型或者它的子类,否则,将无法调用run()方法。 24 | 25 | * 对于Python这样的动态语言来说,则不一定需要传入Animal类型。我们只需要保证传入的对象有一个run()方法就可以了: 26 | ```python 27 | class Timer(object): 28 | def run(self): 29 | print('Start...') 30 | ``` 31 | * 这就是动态语言的“鸭子类型”,它并不要求严格的继承体系,一个对象只要“看起来像鸭子,走起路来像鸭子”,那它就可以被看做是鸭子。 32 | 33 | > Python的“file-like object“就是一种鸭子类型。对真正的文件对象,它有一个read()方法,返回其内容。但是,许多对象,只要有read()方法,都被视为“file-like object“。许多函数接收的参数就是“file-like object“,你不一定要传入真正的文件对象,完全可以传入任何实现了read()方法的对象。 34 | 35 | 36 | ------- 37 | 38 | # 1 完全拷贝 和 复制地址 39 | ### 1 list 拷贝 40 | > Remember that if you want to make a copy of a list or such kinds of sequences or complex objects (not simple objects such as integers), then you have to use the slicing operation to make a copy. If you just assign the variable name to another name, both of them will ''refer'' to the same object and this could be trouble if you are not careful. 41 | 42 | ```python 43 | print('Simple Assignment') 44 | shoplist = ['apple', 'mango', 'carrot', 'banana'] 45 | # mylist is just another name pointing to the same object! 46 | mylist = shoplist 47 | 48 | # I purchased the first item, so I remove it from the list 49 | del shoplist[0] 50 | 51 | print('shoplist is', shoplist) 52 | print('mylist is', mylist) 53 | # Notice that both shoplist and mylist both print 54 | # the same list without the 'apple' confirming that 55 | # they point to the same object 56 | 57 | print('Copy by making a full slice') 58 | # Make a copy by doing a full slice 59 | mylist = shoplist[:] 60 | # Remove first item 61 | del mylist[0] 62 | 63 | print('shoplist is', shoplist) 64 | print('mylist is', mylist) 65 | # Notice that now the two lists are different 66 | ``` 67 | 68 | ### 2 copy 模块 包含 copy()和 deepcopy()两个函数 69 | ```python 70 | import copy 71 | list1=[1,2,3,4,5] 72 | list2=copy.copy(list1)###产生一个新的独立的列表 73 | list3=list1 ## 变量名指向列表 74 | list1.append(7) 75 | print(list1,list2,list3) 76 | 77 | list4=[12,3,4,[23,3,4],5] 78 | list5=list4 79 | list6=copy.deepcopy(list4)###完全复制创建新的列表中列表 80 | list7=copy.copy(list4)###只创建了外层 内层还是指向原列表 81 | list4.append(1111) 82 | list4[3].append(22222) 83 | ``` 84 | 85 | ------- 86 | 87 | # 2 os 目录文件 88 | #### 1 创建目录 89 | > 在Python中可以使用os.mkdir()函数创建目录(创建一级目录)。 90 | ```python 91 | os.mkdir(path) 92 | 93 | ## 其参数path 为要创建目录的路径。 94 | ``` 95 | * 例如要在D盘下创建hello的目录 96 | 97 | ```python 98 | >>> import os 99 | >>> os.mkdir('d:\hello') 100 | ``` 101 | 102 | #### 2 os.makedirs()函数创建多级目录。 103 | 104 | * 如在D盘下创建books的目录,books目录下在创建book目录 105 | ```python 106 | >>> import os 107 | >>>os.makedirs('d:\\books\\book') 108 | ``` 109 | 110 | #### 3 删除目录 111 | > 在Python中可以使用os.rmdir()函数删除目录。 112 | ```python 113 | os.rmdir(path) 114 | 其参数path 为要删除的目录的路径。 115 | ``` 116 | * 例如把D盘下的hmm的目录删除 117 | ```python 118 | >>> import os 119 | >>> os.rmdir('d:\hmm') 120 | ``` 121 | 122 | #### 4 删除多级目录 123 | > 在Python中可以使用os.removedirs()函数删除多级目录。 124 | ```python 125 | os.removdirs(path) 126 | # 其参数path 为要删除的多级目录的路径。 127 | 128 | ``` 129 | 130 | ```python 131 | >>> import os 132 | >>> os.removedirs('d:\\books\\book') 133 | ``` 134 | **注意:要删除的目录必须是空目录** 135 | 136 | #### 5 删除文件 137 | > 在Python中可以使用os.remove()函数删除文件(注意一定是一个文件)。 138 | ```python 139 | os.remov(path) 140 | 其参数path 为要删除的文件的路径。 141 | ``` 142 | 143 | * 如删除D盘下books目录下book目录中的book.txt的文件 144 | 145 | 146 | ```python 147 | >>> import os 148 | >>>os.remove('d:\\books\\book\\book.txt') 149 | ``` 150 | 151 | #### 6 遍历目录 152 | > 在Python中可以使用os.walk()函数遍历目录。 153 | ```python 154 | os.walk(path) 155 | #其参数path 为要遍历的目录,遍历path,返回一个对象,他的每个部分都是一个三元组 ('目录x',[目录x下的目录list],目录x下面的文件) 。 156 | 如: 157 | ``` 158 | 159 | ```python 160 | >>> a=os.walk('d:\\books') 161 | >>> def fun(): 162 | for i in a: 163 | print i 164 | >>> fun() 165 | ('d:\\books', ['book'], ['aa.txt']) 166 | ('d:\\books\\book', [ ], [ ]) 167 | ``` 168 | #### 7 判断是否为目录 169 | > 在Python中可以使用os.path.isdir()函数判断某一路径是否为目录。 170 | ```python 171 | os.path.isdir(path) 172 | #其参数 path为 要进行判断的路径。如果是则返回TRUE,否则返回FALSE。 173 | ``` 174 | #### 8 判断是否为文件 175 | > 在Python中可以使用os.path.isfile()函数判断某一路径是否为文件。 176 | ```python 177 | os.path.isfile(path) 178 | 其参数path为要进行判断的路径。如果是则返回TRUE,否则返回FALSE。 179 | ``` 180 | 181 | 182 | --------- 183 | 184 | # 3 Unicode 185 | 186 | * 在计算机内存中,统一使用Unicode编码,当需要保存到硬盘或者需要传输的时候,就转换为UTF-8编码。 187 | 188 | * 用记事本编辑的时候,从文件读取的UTF-8字符被转换为Unicode字符到内存里,编辑完成后,保存的时候再把Unicode转换为UTF-8保存到文件: 189 | * [服务器字符编码:浏览网页的时候,服务器会把动态生成的Unicode内容转换为UTF-8再传输到浏览器](https://cdn.liaoxuefeng.com/cdn/files/attachments/001387245979827634fd6204f9346a1ae6358d9ed051666000/0) 190 | 191 | 192 | * [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets"](https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/) 193 | 194 | * [Python Unicode Howto](https://docs.python.org/3/howto/unicode.html) 195 | 196 | * [Pragmatic Unicode talk by Nat Batchelder](https://nedbatchelder.com/text/unipain.html) 197 | 198 | 199 | ---------- 200 | 201 | # 4 正则表达式 regex: 文本描述方法 202 | ### 1 创建对象 compile() 203 | 204 | ```python 205 | import re #包含所有正则表达式模块 206 | 207 | re.compile()#传入字符 返回一个regex对象 208 | re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')## r--原始字符串 209 | ``` 210 | 211 | ### 2 匹配对象 212 | #### 1 search() 包含第一次搜到的文本 213 | 214 | ```python 215 | phonenumber_regex=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') 216 | mo = phonenumber_regex.search('my number i s 123-234-4557') 217 | ##search搜到返回 Mark对象 没有 返回None 218 | mo.group() 219 | ###调用Match对象的group方法 220 | 221 | ``` 222 | 223 | #### 2 findall() 返回所有的字符串列表或者元组列表 224 | 225 | * 1. 没有分组的正则表达式返回字符串列表 226 | * 2. 分组的正则表达式返回元组的列表 227 | 228 | ### 3 利用符号 匹配更多模式 229 | #### 1 括号--分组 230 | 231 | ```python 232 | phonenum_regex=re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d)') 233 | mo=phonenum_regex.search(message1) 234 | print('\n'+mo.group(1))##参数为0或者空 返回整个文本 235 | areacode,b=mo.groups()###groups 返回所有分组 236 | print('\n' + 'areacode:'+areacode +' b: ' +b) 237 | ``` 238 | 239 | #### 2 利用管道'|' 匹配多个分组 240 | 241 | ```python 242 | message2='Batman and TomFord' 243 | message3='TomFord and Batman' 244 | 245 | hero_regex=re.compile(r'Batman|TomFord') 246 | mo=hero_regex.search(message2) 247 | print('\n'+ mo.group()) 248 | 249 | mo=hero_regex.search(message3) 250 | print('\n'+ mo.group()) 251 | ###多通道的时候 返回第一次出现的字符 252 | ``` 253 | 254 | #### 3 用问号实现可选分配 ;匹配 1次或者0次 255 | 256 | ```python 257 | # 字符 ?表明它的前面的分组在这个模式中是可选的 258 | bat_regex= re.compile(r'Bat(wo)?man') 259 | mo=bat_regex.search('The Adventures of Batman') 260 | if mo !=None: 261 | print('\n'+mo.group()) 262 | 263 | mo=bat_regex.search('The Adventures of Batmaen') 264 | if mo !=None: ### 265 | print('\n'+mo.group()) 266 | else: 267 | print('\nNone') 268 | ``` 269 | 270 | #### 4 利用*号匹配 零次或者多次 加号+匹配一次或者多次 271 | 272 | ```python 273 | bat_regex= re.compile(r'Bat(wo)*man') 274 | mo=bat_regex.search('The Adventures of Batman') 275 | if mo !=None: 276 | print('\n'+mo.group()) 277 | mo=bat_regex.search('The Adventures of Batwowowoman') 278 | if mo !=None: 279 | print('\n'+mo.group()) 280 | ``` 281 | 282 | #### 5 花括号匹配特定次数{} 283 | 284 | ```python 285 | (liu){3}匹配3次 286 | (liu){3,5}匹配3-5次 287 | (liu){3,}3到更多次 288 | (liu){,5}0-5次 289 | ``` 290 | 291 | ### 4 贪心与非贪心匹配 292 | * 1 贪心:默认 在有很多匹配的时候 匹配最长的字符串 293 | * 2 非贪心:在{}后面加上一个? 匹配最短的字符串 294 | 295 | ### 5 常用缩写字符分类 296 | | 缩写字符 | 表示 | 297 | | ----- | -- | 298 | | \d | 0-9任何数字 | 299 | | \d+ | 0-9任何数字(一个或者多个数字) | 300 | | \D | 0-9外所有字符 | 301 | | \w | 任何字母数字或者下划线字符| 302 | | \W | 除去字母数字或者下划线字符| 303 | | \s | 空格 制傅表 或者换行符| 304 | | \S | 除去空格 制傅表 或者换行符| 305 | 306 | ### 6 建立自己的字符分类 []定义 307 | 308 | * 1. r'[aeiouAEIOU]' :匹配所有的元音 309 | * 2. r'[a-zA-Z0-9]':匹配所有的字母数字 310 | * 3. 插入'^' 表示反义 (r'[^aeiouAEIOU]') 311 | 312 | ### 7 '$' and '^' 313 | 314 | * 1. '^' 匹配最开始处 315 | * 2. '$' 以该正则模式结束 : r'\d$' -- 以0-9 数字结束 316 | * 3. '^\d$'---从开头到结尾都是数字 317 | 318 | ### 8 通配字符 319 | #### 1 '.'匹配 除了换行之外 所有的字符(值匹配 一个字符) 320 | 321 | ```python 322 | at_regex=re.compile(r'.at') 323 | ``` 324 | 325 | #### 2 '.*'匹配 所有字符 默认贪心模式 326 | 327 | ```python 328 | # * 表示前面字符出现零次或者多次 329 | name_regex=re.compile(r'First Name: (.*) Last Name: (.*)') 330 | 331 | #非贪心模式 尽可能短 加? 332 | (.*?) 333 | ``` 334 | 335 | #### 3 传入 re.DOTALL 句点字符匹配换行 336 | 337 | ```python 338 | new_regex=re.compile(r'.*',re.DOTALL) 339 | ``` 340 | 341 | ### 9 大小写匹配 传入re.IGNORECASE or re.I 则 大小写皆可替换 342 | 343 | ```python 344 | re.compile(r'LIuchuang',re.I) 345 | ``` 346 | 347 | ### 10 替换字符串 sub() 348 | * sub() 第一个参数为字符串用于取代发现的匹配,第二个为待修改的字符串。 349 | 350 | ```python 351 | name_regex=re.compile(r'Agent \w+') 352 | name_regex.sub('Liu','Agent LIuchuang Gave kd kk KK ') 353 | ``` 354 | 355 | ### 11 复杂的正则表达式 传入 re.VERBOSE 进行分行 356 | 357 | ```python 358 | phone_regex=compile(r'''( 359 | (\d{3})|\(d{3}\))? ##可选分组 区号121 或者(112) 360 | (\s|-|\.)? ### 分隔符 361 | \d{3} ###前三位 362 | (\s|-|\.) 363 | \d{4})###后四位 364 | ''',re.VERBOSE) 365 | ``` 366 | 367 | ---------- 368 | 369 | 370 | 371 | # 5 字符串 372 | ### 1字符串类型 373 | ![](https://images2018.cnblogs.com/blog/884071/201711/884071-20171127154213565-171071034.png) 374 | * 由于Python的字符串类型是str,在内存中以Unicode表示,一个字符对应若干个字节。如果要在网络上传输,或者保存到磁盘上,就需要把str变为以字节为单位的bytes 375 | 376 | ```python 377 | 'ABC'.encode('ascii') 378 | '中文'.encode('utf-8') 379 | ``` 380 | 381 | * 反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法 382 | 383 | ```python 384 | b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore')#忽略错误字节 385 | ``` 386 | 387 | * 要计算str包含多少个字符,可以用len()函数: 388 | ```python 389 | len('ABC') 390 | len("中国话") 391 | ``` 392 | 393 | ### 2 字符串方法 394 | > 这些方法没有改变字符串本身 ,而是返回一个新的字符串 395 | 396 | * 1 upper(),lower() 397 | 398 | ```python 399 | str=str.upper() 400 | ``` 401 | 402 | * 2 isupper(),islower() 403 | ```python 404 | str.isupper() :所有字母都是大写 返回True 405 | str.islower() 406 | 407 | isalpha():只包含字母 并且非空 408 | isdecimal():只包含数字 并且非空 409 | isalnum():只包含字母数字并且非空 返回True 410 | isspace(): 只包含 空格制表符和换行,并且非空 411 | istitle():字符串 包含以大写字母开头 后面都是小写的单词 412 | ``` 413 | 414 | * 415 | ```python 416 | * str.isalnum() 所有字符都是数字或者字母 417 | * str.isalpha() 所有字符都是字母 418 | * str.isdigit() 所有字符都是数字 419 | * str.islower() 所有字符都是小写 420 | * str.isupper() 所有字符都是大写 421 | * str.istitle() 所有单词都是首字母大写,像标题 422 | * str.isspace() 所有字符都是空白字符、\t、\n、\ 423 | 424 | ``` 425 | **循环输入直到有效输入** 426 | 427 | * 3 startwith(),endwith() 428 | 429 | ```python 430 | #判断字符串开头结尾 431 | 'Hello World'.startwith('Hello') 432 | ``` 433 | 434 | * 4 join() 和 split() 435 | 436 | ```python 437 | #join()在一个字符串上调用,参数为字符串列表,返回一个字符串 438 | ','.join(['hello','world']) 439 | 440 | #split() 在一个字符串上调用 返回列表 441 | 'hello world'.split()#,默认以空白字符串分割 442 | `helloABCworldABCoh'.split('ABC') 443 | ''.split('\n')#以换行符 切割 多行字符串 444 | ``` 445 | 446 | * 5 rjust();ljust,center() 左右中心对齐 447 | 448 | ```python 449 | 'Hello'.rjust(20,'*')#总长度为20 第二个参数为填充字符 450 | ``` 451 | 452 | * 6 rtrip(),ltrip(),strip() :删除 空白字符(空格制表符,换行符),返回新的字符串 453 | 454 | ```python 455 | str=str.rtrip() 456 | 457 | str.strip('abc')#删除两边的字符 顺序不重要 出现既可以删除 458 | ``` 459 | 460 | 461 | ---------- 462 | 463 | 464 | # 6 print 格式化 代替 465 | 466 | ```python 467 | print("%s : %d",%('L.C',23)) 468 | 469 | #%d整数 470 | 471 | print('%2d-%03d' % (300, 1))#03 在1 前面补位 n-1个0 472 | 473 | #%f浮点数 474 | 475 | print('%.2f' % 3.1415926)#保留两位小数 476 | 477 | #%s字符串 478 | #%z 十六进制整数 479 | ``` 480 | * [f-strings](https://docs.python.org/3/whatsnew/3.6.html#new-features) 481 | 482 | 483 | ## 4漂亮打印- 字典存在嵌套时 484 | 从程序中导入pprint模块 使用pprint()函数 使得键值排序 485 | ```python 486 | message="I love you 'Zou Xiaowei'" 487 | count={} 488 | 489 | for character in message: 490 | count.setdefault(character,0) 491 | count[character]+=1 492 | print(count) 493 | pprint.pprint(count) 494 | 495 | ``` 496 | ---------- 497 | 498 | 499 | 500 | 501 | 502 | # 7 函数 503 | 504 | ### 1 默认参数 505 | > 默认参数可以简化函数的调用。设置默认参数时,有几点要注意: 506 | * 一是必选参数在前,默认参数在后,否则Python的解释器会报错(思 考一下为什么默认参数不能放在必选参数前面); 507 | * 二是如何设置默认参数。当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。 508 | 509 | **定义默认参数要牢记一点:默认参数必须指向不变对象!** 510 | 511 | ### 2函数的参数改为可变参数(参数前加一个* )任意数量的实参 512 | * 1. 513 | 514 | ```python 515 | def calc(*numbers): # 创建一个空元祖 516 | sum = 0 517 | for n in numbers: 518 | sum = sum + n * n 519 | return sum 520 | >>> calc(1, 2) 521 | 5 522 | >>> calc() 523 | 0 524 | ``` 525 | 526 | * 2.任意数量关键字实参: 527 | > 函数 接受任意数量的 K-V值 528 | ```python 529 | def fun(first,last,**user_info): 530 | ``` 531 | > *args and **kwargs 532 | *args: 把所有的参数按出现顺序打包成一个 list 533 | **kwargs:把所有 key-value 形式的参数打包成一个 dict 534 | 535 | ### 3 函数 传递列表 536 | #### 1 传递 输入 537 | ```python 538 | def greet_users(names) 539 | for name in names: 540 | print(name) 541 | user_names=[] 542 | greet_users(user_names) 543 | ``` 544 | 545 | #### 2 禁止函数修改 列表 546 | > 将列表的副本传递给函数 547 | ``` 548 | function_name(list_name[:]) 549 | ``` 550 | 551 | ### 4 高级函数 552 | #### 1 map 553 | * map()传入的第一个参数是f,即函数对象本身。由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。 554 | ```python 555 | def f(x): 556 | return x*x 557 | r=list( 558 | map(f,[1,2,3,4,5,6,7])) 559 | print(r) 560 | ``` 561 | 562 | #### 2 reduce 563 | * reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:o 564 | ```python 565 | reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) 566 | ``` 567 | 568 | ### 5 filter 函数 筛选 过滤 569 | #### 1 列表项 570 | * filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。 571 | ```python 572 | def is_odd(s): 573 | return s%2==1 574 | 575 | A=list(filter(is_odd,[1,2,3,4,5,6,7,8,9,89,99])) 576 | print(A) 577 | ``` 578 | 579 | #### 2 应用 580 | **求素数** 581 | 582 | ### 6 匿名函数 583 | ```python 584 | def f(x): 585 | return x*x 586 | 587 | lambda x:x*x 588 | f=lambda x: x*x 589 | 590 | ``` 591 | 592 | 593 | ---------- 594 | # 8 模块 595 | ### 1 导入模块 596 | * 1 导入整个模块 597 | > 在相同目录创建文件, 598 | * pizza.py 包含(make_pizza 函数)and make_pizzas.py 599 | ```python 600 | import pizza 601 | pizza.make_pizza(16) 602 | ``` 603 | 604 | * 2 导入特定函数 605 | 606 | ```python 607 | from pizza import function_0,function_1,function_2 608 | function_0() 609 | ``` 610 | * 3 as 给函数指定别名 611 | 612 | ```python 613 | from pizza import make_pizza as mp 614 | mp() 615 | ``` 616 | 617 | * 4 as 给模块命名 618 | 619 | ```python 620 | import pizza as p##功能描述性名称 621 | p.make_pizza() 622 | ``` 623 | 624 | * 5 导入模块所有函数 625 | ```python 626 | from pizza import * ##复制所有的函数 627 | make_pizza()## 不需要前缀 628 | ``` 629 | 630 | **大型模块不宜使用** 631 | 632 | 633 | ---------- 634 | # 9 类 面向对象编程 635 | ### 1 编码风格 636 | > 定义的一大类对象 有通用行为,基于类 创建对象时 每个对象自动拥有这些行为,根据需要赋予特性 637 | > 首字母 大写指的是类Dog() 638 | * 实例名称和模块名都是小写加下划线 : my_dog 639 | > 类 在定义后 应该包含一个文档字符串 描述功能 640 | * 一个空行分隔 方法def 两个空行分隔 类 641 | * 先导入标准库模块 空一行 导入自己编写的模块 642 | 643 | 644 | ```python 645 | Class Dog(): 646 | __init__(self,name,age)##方法 647 | ##self:调用init时候,自动传入实参self,每个与类相关的方法调用###都自动传递实参self,指向实例的引用,让实例能访问类中的属性方##法。不需要提供数值 648 | self.name=name# self###为前缀的变量可以供类中所有方法使用,类########的实例也可以访问 称为 属性、 649 | ``` 650 | 651 | ### 2 调用 652 | * 创造实例后 句点调用方法 653 | ``` 654 | my_dog=Dog('asd',13) 655 | my_dog.sit() 656 | ``` 657 | 658 | ### 3 添加属性默认值 659 | 660 | ```python 661 | self.name=0 662 | ``` 663 | 664 | ### 4修改属性的值 665 | > 通过方法修改属性的值 666 | ``` 667 | def update(self,m): 668 | self.name=m 669 | ``` 670 | **通过判断 设定修改范围 或者禁止修改** 671 | 672 | ---------- 673 | 674 | # 10 list 675 | 676 | ### 0 list切片 677 | ```python 678 | list[:]##全部 679 | list[-3:]##倒数三个 680 | ``` 681 | 682 | ### 1 写列表生成式时,把要生成的元素x*x放到前面,后面跟for循环,就可以把list创建出来 683 | ```python 684 | A=[x+x for x in range(1,20)] 685 | 686 | B=[x+x for x in range(1,20) if x%2==0] 687 | ``` 688 | 689 | ### 2 列出当前目录下的所有文件和目录名,可以通过一行代码实现: 690 | ```python 691 | E=[d for d in os.listdir('.')] 692 | 693 | ``` 694 | 695 | ### 3 一个list中所有的字符串变成小写 696 | ```python 697 | L = ['Hello', 'World', 'IBM', 'Apple'] 698 | F=[s.lower() for s in L] 699 | M = ['Hello', 'World', 18, 'Apple', None] 700 | G=[q.lower() for q in M if isinstance(q,str) ]#判断是否为字符串 701 | ``` 702 | 703 | ### 4 tuple()不变 list[]可变 704 | > 表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。即指向'a',就不能改成指向'b',指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的! 705 | 理解了“指向不变”后,要创建一个内容也不变的tuple怎么做?那就必须保证tuple的每一个元素本身也不能变。 706 | 707 | * [列表和元组相互转换] 708 | (https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014316724772904521142196b74a3f8abf93d8e97c6ee6000) 709 | 710 | ### 5 列表排序 711 | sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序: 712 | ```python 713 | >>> sorted([36, 5, -12, 9, -21], key=abs) 714 | [5, 9, -12, -21, 36] 715 | 716 | list=[1,2,3,4,5,3,4,2] 717 | list.sort(reserve=True) ##不能记录排序返回值 718 | print(list) 719 | 720 | list=['a','b','D','AA'] 721 | list.sort() #大写排在小写前A面 722 | list.sort(key=str.lower) 723 | ``` 724 | 725 | 726 | ---------- 727 | # 11 集合 set() 728 | 729 | > 1.是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算. 730 | > 2.sets 支持 x in set, len(set),和 for x in set。作为一个无序的集合,sets不记录元素位置或者插入点。因此,sets不支持 indexing, slicing, 或其它类序列(sequence-like)的操作。 731 | 732 | ```python 733 | A=set([1,2,3,4]) 734 | B=set([1,2,3]) 735 | A|B #并集 736 | A&B #交集 737 | A-B #差集 738 | list(A) #转为列表 739 | [i for i in A] # 转为列表 740 | 741 | ``` 742 | ```python 743 | len(s) #set 的长度 744 | x in s #测试 x 是否是 s 的成员 745 | x not in s #测试 x 是否不是 s 的成员 746 | s.issubset(t) 747 | s <= t 748 | #测试是否 s 中的每一个元素都在 t 中 749 | 750 | s.issuperset(t) 751 | s >= t 752 | #测试是否 t 中的每一个元素都在 s 中 753 | 754 | s.union(t) 755 | s | t 756 | #返回一个新的 set 包含 s 和 t 中的每一个元素 757 | 758 | s.intersection(t) 759 | s & t 760 | #返回一个新的 set 包含 s 和 t 中的公共元素 761 | 762 | s.difference(t) 763 | s - t 764 | #返回一个新的 set 包含 s 中有但是 t 中没有的元素 765 | 766 | s.symmetric_difference(t) 767 | s ^ t 768 | #返回一个新的 set 包含 s 和 t 中不重复的元素 769 | 770 | s.copy() ##返回 set “s”的一个浅复制 771 | ``` 772 | 773 | 774 | ------ 775 | 776 | # 12 tuple 元组 777 | ### 1 赋值顺序 778 | ```python 779 | a = 3 780 | a, b = 1, a 781 | print('a=',a,'\n''b=',b) 782 | 783 | 输出:a= 1 784 | b= 3 785 | ``` 786 | 787 | > 如果按正常思维肯定是先将1赋值给a,然后再将a值赋给b,实际上也确实是这样的,但是前面提到这样赋值其实右边相当于一个元组tuple,而tuple中的元素是不变的,所以后面的b=a中的a相当于t(1)是不变的,是前面a=3就已经确定好的,就是说a, b = 1, a这条语句是先执行右边即先创建一个元组,然后再是分为两条语句执行的先将1赋值给a,然后将元组中的a赋值给b 788 | 789 | ```python 790 | max, min = min, max 791 | #同时执行 不等价 分别min=max,max=min 792 | print(max(1, 2, 3, 4, 5)) 793 | ``` 794 | ### 2元组() 795 | * 1.元组内数据不能赋值 796 | * 2 但是可给储存元组的变量赋值 797 | 798 | ### 3 应用 799 | 1 禁止修改图片尺寸 800 | 2 自助菜单点菜 两份菜单 801 | 802 | 803 | ---------- 804 | 805 | 806 | 807 | # 13 迭代器 和装饰器 808 | ### 1 迭代器判断 809 | * 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。可以使用isinstance()判断一个对象是否是Iterator对象: 810 | 811 | ```python 812 | >>> from collections import Iterator 813 | isinstance((x for x in range(10)), Iterator) 814 | isinstance([], Iterator) 815 | ``` 816 | 817 | ### 2 转换成迭代器 818 | * 把list、dict、str等Iterable变成Iterator可以使用iter()函数: 819 | ```python 820 | isinstance(iter([]), Iterator) 821 | ``` 822 | ### 3 装饰器 823 | > def:在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。 824 | 825 | * [1装饰器原理](https://www.zhihu.com/question/26930016/answer/99243411 ) 826 | * [2装饰器使用](https://blog.csdn.net/MDL13412/article/details/22608283) 827 | ```python 828 | import time 829 | def func(): 830 | print("hello") 831 | time.sleep(1) 832 | print("world") 833 | 834 | #原始侵入,篡改原函数 835 | def func1(): 836 | startTime=time.time() 837 | print("hello") 838 | time.sleep(3) 839 | print("world") 840 | endTime=time.time() 841 | mes=(endTime - startTime)*100 842 | print('time is %d ms'%mes) 843 | 844 | func1() 845 | #装饰器就像一个注入符号:有了它,拓展了原来函数的功能既不需要侵入函数内更改代码,# 846 | #也不需要重复执行原函数。 847 | def deco(func2): 848 | def wrapp(): 849 | startTime=time.time() 850 | func2() 851 | endTime=time.time() 852 | mes=(endTime - startTime)*100 853 | print('time is %d ms'%mes) 854 | return wrapp 855 | 856 | @deco 857 | def func2(): 858 | print('hello') 859 | time.sleep(4) 860 | print('world') 861 | 862 | func2() 863 | 864 | ##带有参数的装饰器 865 | def deco1(func3): 866 | def wrapp1(a,b): 867 | startTime=time.time() 868 | func3(a,b) 869 | endTime=time.time() 870 | mes=(endTime - startTime)*100 871 | print('TIME is %d ms'%mes) 872 | return wrapp1 873 | 874 | @deco1 875 | def func3(a,b): 876 | print('hello') 877 | time.sleep(0.3) 878 | print('sb') 879 | print('a+b =%d'%(a+b)) 880 | func3(5,6) 881 | 882 | ##带有不定参数的装饰器 883 | def deco2(func4): 884 | def wrapper(*args, **kwargs): 885 | startTime = time.time() 886 | func4(*args, **kwargs) 887 | endTime = time.time() 888 | msecs = (endTime - startTime)*1000 889 | print("time is %d ms" %msecs) 890 | return wrapper 891 | 892 | @deco2 893 | def func4(a,b): 894 | print("hello,here is a func for add :") 895 | time.sleep(1) 896 | print("result is %d" %(a+b)) 897 | 898 | @deco2 899 | def func5(a,b,c): 900 | print("hello,here is a func :") 901 | time.sleep(0.4) 902 | print("result is %d" %(a+b+c)) 903 | 904 | 905 | if __name__ == '__main__': 906 | f = func4 907 | func5(3,4,5) 908 | f(3,4) 909 | #func() 910 | 911 | def deco01(func): 912 | def wrapper(*args, **kwargs): 913 | print("this is deco01") 914 | startTime = time.time() 915 | func(*args, **kwargs) 916 | endTime = time.time() 917 | msecs = (endTime - startTime)*1000 918 | print("time is %d ms" %msecs) 919 | print("deco01 end here") 920 | return wrapper 921 | 922 | def deco02(func): 923 | def wrapper(*args, **kwargs): 924 | print("this is deco02") 925 | func(*args, **kwargs) 926 | 927 | print("deco02 end here") 928 | return wrapper 929 | 930 | @deco01 931 | @deco02 932 | def func(a,b): 933 | print("hello,here is a func for add :") 934 | time.sleep(1) 935 | print("result is %d" %(a+b)) 936 | 937 | if __name__ == '__main__': 938 | f = func 939 | f(3,4) 940 | #func() 941 | ``` 942 | 943 | 944 | 945 | # 14 随机数 946 | * [在线字符串生成随机数生成](http://tools.jb51.net/aideddesign/suijishu) 947 | * [高密度字符串密码](http://tools.jb51.net/password/CreateStrongPassword) 948 | 949 | ```python 950 | print(random.uniform(10, 20)) 951 | print(random.uniform(20, 10)) 952 | 953 | 用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,Python生成随机数 954 | 955 | print(random.randint(12, 20)) #生成的随机数n: 12 <= n <= 20 956 | print(random.randint(20, 20)) #结果永远是20 957 | print(random.randint(20, 10)) #该语句是错误的,下限必须小于上限。 958 | random.randrange 959 | ``` 960 | 961 | * 随机整数 962 | ```python 963 | : 964 | >>> import random 965 | >>> random.randint(0,99) 966 | 21 967 | ``` 968 | 969 | * 随机选取0到100间的偶数: 970 | ```python 971 | >>> import random 972 | >>> random.randrange(0, 101, 2) 973 | 42 974 | ``` 975 | * 随机浮点数: 976 | 977 | ```python 978 | >>> import random 979 | >>> random.random() 980 | 0.85415370477785668 981 | >>> random.uniform(1, 10) 982 | 5.4221167969800881 983 | ``` 984 | 985 | * 随机字符 986 | ```python 987 | >>> import random 988 | >>> random.choice('abcdefg&#%^*f') 989 | 'd' 990 | ``` 991 | 992 | * 多个字符中选取特定数量的字符 993 | ```python 994 | >>> import random 995 | random.sample('abcdefghij',3) 996 | ['a', 'd', 'b'] 997 | ``` 998 | 999 | * 多个字符中选取特定数量的字符组成新字符串 1000 | ```python 1001 | >>> import random 1002 | >>> import string 1003 | >>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r 1004 | eplace(" ","") 1005 | 'fih' 1006 | ``` 1007 | 1008 | * 随机选取字符串: 1009 | ```python 1010 | >>> import random 1011 | >>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] ) 1012 | 'lemon' 1013 | ``` 1014 | * 洗 1015 | ```python 1016 | >>> import random 1017 | >>> items = [1, 2, 3, 4, 5, 6] 1018 | >>> random.shuffle(items) 1019 | >>> items 1020 | [3, 2, 5, 6, 4, 1] 1021 | ``` 1022 | -------- 1023 | 1024 | 1025 | 1026 | # 15 字典 1027 | ![](https://raw.githubusercontent.com/LiuChuang0059/gitpic/master/dict_time.png) 1028 | ### 1 添加 修改 删除键值对 1029 | ```python 1030 | alien_0={} 1031 | alien_0['color']='green' 1032 | alien_0['point']=5 1033 | del alien_0['point'] #k-v del the same time 1034 | 1035 | ``` 1036 | ### 2 setfault()确保一个键值的存在 1037 | ```python 1038 | ###setdefault()第一个参数检查是否存在该键值 1039 | ###第二个参数 ,如果键值存在,返回键值,不存在 设置添加键值 1040 | dict1={'a':1,'b':2} 1041 | print(dict1.setdefault('c',3)) 1042 | print(dict1) 1043 | 1044 | ##查找各个字符出现的次数 1045 | message="I love you 'Zou Xiaowei'" 1046 | count={} 1047 | for character in message: 1048 | count.setdefault(character,0)##确保字典里面有该键值 1049 | count[character]+=1 1050 | print(count) 1051 | ``` 1052 | ### 3 get获取键值:如果不存在,返回备用值 1053 | ``` 1054 | dict1={'a':1,'b':2} 1055 | a=dict1.get('a','None') 1056 | c=dict1.get('c','None') 1057 | print(a,c) 1058 | ``` 1059 | ### 4 遍历字典 1060 | ``` 1061 | for k,v in alien_0.items():#遍历所有 key value 1062 | 1063 | for k in alien_0.keys():# 只遍历 key 1064 | for k in alien_0 #等价上语句 1065 | ``` 1066 | ### 5 .keys()返回一个列表 1067 | > 通过sorted() 对 字典进行排序 1068 | ``` 1069 | for k in sorted(alien_0.keys()): 1070 | ``` 1071 | 1072 | ### 6 字典重复项 set() 去除 1073 | ``` 1074 | for value in set(alien_0.values()): 1075 | ``` 1076 | 1077 | ### 7 迭代 value 1078 | * 默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values(), 1079 | * 如果要同时迭代key和value,可以用for k, v in d.items()。 1080 | 1081 | 1082 | ### 6嵌套 1083 | #### 1 包含字典的列表 1084 | ```python 1085 | #产生不同的外星人 1086 | alien_0={'color':'green','point':5} 1087 | alien_1={'color':'red','point':10} 1088 | alien_2={'color':'yellow','point':15} 1089 | aliens=[alien_0,alien_1,alien_2] 1090 | for i in aliens: 1091 | print(i) 1092 | ``` 1093 | 1094 | ```python 1095 | #批量外星人 1096 | alien={'color':'green','point':5} 1097 | aliens=[] 1098 | for i in range(1,10): 1099 | aliens.append(alien) 1100 | for i in aliens[-3:-1]: 1101 | print(i) 1102 | print(len(aliens)) 1103 | ``` 1104 | ```python 1105 | #???????? 1106 | aliens=[] 1107 | for i in range(1,10): 1108 | alien1={'color':'green','point':5}###不能放在for外面??? 1109 | aliens.append(alien1) 1110 | 1111 | #批量修改外星人 1112 | for alien in aliens[:1]: 1113 | if alien['color']== 'green': 1114 | alien['color']='blue' 1115 | alien['point']= 2 1116 | elif alien['color']=='red': 1117 | alien['color']='xxx' 1118 | alien['point']= 21 1119 | for alien in aliens[0:6]: 1120 | print(alien) 1121 | ``` 1122 | 1123 | #### 2 包含list 的dict(一个key 关联很多信息) 1124 | ```python 1125 | information={ 1126 | 'Name':'Liu Chuang', 1127 | 'Age':20, 1128 | 'School':['Haiwan','37th','Wuhan University'], 1129 | 'ideal':['Zhejiang','Peking'], 1130 | } 1131 | print('Name: '+ information['Name']+ '\n') 1132 | print('Age: '+ str(information['Age'])+ '\n') 1133 | print('\nSchool:') 1134 | for school in information['School']: 1135 | print(school) 1136 | print('\nIdeal:') 1137 | for ideal in information['ideal']: 1138 | print(ideal) 1139 | ``` 1140 | #### 3 字典嵌套字典 1141 | > * 登记学生信息 有很多学生 每个学生有几个信息 1142 | 1143 | ```python 1144 | cities={ 1145 | 'Dalian':{ 1146 | 'Location':'A+', 1147 | 'Environment':'A+', 1148 | 'consume':'B+' 1149 | }, 1150 | 'Hangzhou':{ 1151 | 'Location':'A', 1152 | 'Environment':'A+', 1153 | 'consume':'A+' 1154 | }, 1155 | 'Shenzhen':{ 1156 | 'Location':'A', 1157 | 'Environment':'A', 1158 | 'consume':'A+' 1159 | }, 1160 | } 1161 | 1162 | cities['Dalian']['Location']='A-' ## 修改字典中的Value 1163 | cities['DaLian']=cities.pop('Dalian')##修改字典的Key 1164 | for city,infor in cities.items(): 1165 | print('\n'+city +' :') 1166 | ##另一个字典 1167 | for facter,rank in infor.items(): 1168 | print('\t'+facter +': '+ rank) 1169 | 1170 | ``` 1171 | 1172 | ------- 1173 | 1174 | # 16 While 循环 1175 | ### 1 单个事件控制循环退出 1176 | ```python 1177 | while message!= 'quit' 1178 | ``` 1179 | ### 2 多个事件导致停止 引入“标志” 1180 | ```python 1181 | act=True 1182 | while act : 1183 | message=input(prompt) 1184 | if message == 'quit': 1185 | act=False 1186 | elif message == 'QUIT': 1187 | act=False 1188 | else: 1189 | print(message) 1190 | ``` 1191 | ### 3 break vs continue 1192 | * break 跳出循环 1193 | * continue 忽略后面代码 从while 执行 1194 | 1195 | ----------- 1196 | 1197 | # 17 异常 1198 | ### try--except--else 模块 1199 | * 将可能引发异常的代码放入try语句 1200 | * 在try成功执行的代码放入else 1201 | * except 代码 对应错误类型 以及 引发错误该怎么办 1202 | 1203 | -------- 1204 | 1205 | # 18 代码测试 unittest 1206 | > 运行测试实例时,完成一个测试单元,python打印一个字符: 1207 | * 通过一个测试,打印一个句点; 1208 | * 测试引发错误时,打印一个E, 1209 | * 测试导致断言失败时候 打印一个F。 1210 | 1211 | ### 1 测试函数 1212 | 1213 | ### 2 测试类 1214 | * 断言方法 1215 | 1216 | 1217 | | 方法 | 用途 | 1218 | | -------- | -----: | 1219 | | assertEqual(a,b) | a==b | 1220 | | assertTrue(x) | x为True | 1221 | | assertIn(item,list) | 核实item在list中 | 1222 | | assertNotEqual(a,b) | a!=b | 1223 | | assertFalse(x) | x为False | 1224 | | assertNotIn(item,list) | 核实item不在list中 | 1225 | 1226 | ---------- 1227 | 1228 | 1229 | -------------------------------------------------------------------------------- /python_fundamental/backup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Apr 18 23:14:17 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | import os 9 | import time 10 | 11 | # 1. The files and directories to be backed up are 12 | # specified in a list. 13 | # Example on Windows: 14 | source = ['"C:\\My Documents"'] 15 | # Example on Mac OS X and Linux: 16 | #source = ['/Users/swa/notes'] 17 | # Notice we have to use double quotes inside a string 18 | # for names with spaces in it. We could have also used 19 | # a raw string by writing [r'C:\My Documents']. 20 | 21 | # 2. The backup must be stored in a 22 | # main backup directory 23 | # Example on Windows: 24 | target_dir = 'E:\\Bac' 25 | # Example on Mac OS X and Linux: 26 | #target_dir = '/Users/swa/backup' 27 | # Remember to change this to which folder you will be using 28 | 29 | # 3. The files are backed up into a zip file. 30 | # 4. The name of the zip archive is the current date and time 31 | target = target_dir + os.sep + \ 32 | time.strftime('%Y%m%d%H%M%S') + '.zip' 33 | 34 | # Create target directory if it is not present 35 | if not os.path.exists(target_dir): 36 | os.mkdir(target_dir) # make directory 37 | # 3. The files are backed up into a zip file. 38 | # 4. The current day is the name of the subdirectory 39 | # in the main directory. 40 | today = target_dir + os.sep + time.strftime('%Y%m%d') 41 | # The current time is the name of the zip archive. 42 | now = time.strftime('%H%M%S') 43 | 44 | # The name of the zip file 45 | target = today + os.sep + now + '.zip' 46 | 47 | # Create the subdirectory if it isn't already there 48 | if not os.path.exists(today): 49 | os.mkdir(today) 50 | print('Successfully created directory', today) 51 | # 5. We use the zip command to put the files in a zip archive 52 | zip_command = 'zip -r {0} {1}'.format(target, 53 | ' '.join(source)) 54 | 55 | # Run the backup 56 | print('Zip command is:') 57 | print(zip_command) 58 | print('Running:') 59 | if os.system(zip_command) == 0: 60 | print('Successful backup to', target) 61 | else: 62 | print('Backup FAILED') 63 | -------------------------------------------------------------------------------- /python_fundamental/backuprefresh.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Apr 19 11:31:25 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | import os 9 | import time 10 | 11 | # 1. The files and directories to be backed up are 12 | # specified in a list. 13 | # Example on Windows: 14 | source = ['"C:\\My Documents"'] 15 | # Example on Mac OS X and Linux: 16 | #source = ['/Users/swa/notes'] 17 | # Notice we had to use double quotes inside the string 18 | # for names with spaces in it. 19 | 20 | # 2. The backup must be stored in a 21 | # main backup directory 22 | # Example on Windows: 23 | target_dir = 'E:\\Backup2' 24 | # Example on Mac OS X and Linux: 25 | #target_dir = '/Users/swa/backup' 26 | # Remember to change this to which folder you will be using 27 | 28 | # Create target directory if it is not present 29 | if not os.path.exists(target_dir): 30 | os.mkdir(target_dir) # make directory 31 | 32 | # 3. The files are backed up into a zip file. 33 | # 4. The current day is the name of the subdirectory 34 | # in the main directory. 35 | today = target_dir + os.sep + time.strftime('%Y%m%d') 36 | # The current time is the name of the zip archive. 37 | now = time.strftime('%H%M%S') 38 | 39 | # Take a comment from the user to 40 | # create the name of the zip file 41 | comment = input('Enter a comment --> ') 42 | # Check if a comment was entered 43 | if len(comment) == 0: 44 | target = today + os.sep + now + '.zip' 45 | else: 46 | target = today + os.sep + now + '_' + \ 47 | comment.replace(' ', '_') + '.zip' 48 | 49 | # Create the subdirectory if it isn't already there 50 | if not os.path.exists(today): 51 | os.mkdir(today) 52 | print('Successfully created directory', today) 53 | 54 | # 5. We use the zip command to put the files in a zip archive 55 | zip_command = 'zip -r {0} {1}'.format(target, 56 | ' '.join(source)) 57 | 58 | # Run the backup 59 | print('Zip command is:') 60 | print(zip_command) 61 | print('Running:') 62 | if os.system(zip_command) == 0: 63 | print('Successful backup to', target) 64 | else: 65 | print('Backup FAILED') 66 | -------------------------------------------------------------------------------- /python_fundamental/class.import.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue May 15 16:43:57 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | from class_son9798 import Admin 9 | 10 | zou=Admin('Zou','Xiaowei',19) 11 | zou.show.show_privileges() 12 | zou.greetr_user() 13 | 14 | -------------------------------------------------------------------------------- /python_fundamental/class.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue May 15 00:41:17 2018 4 | 5 | @author: lc 6 | 创建一个类 包含属性方法 7 | 8 | """ 9 | 10 | 11 | class User(): 12 | """ user""" 13 | def __init__(self,first_name,last_name,age,weight): 14 | self.first_name=first_name 15 | self.last_name=last_name 16 | self.age=age 17 | self.weight=weight 18 | def describe_user(self): 19 | print(self.first_name,self.age) 20 | def greetr_user(self): 21 | print(self.age) 22 | liu=User('Liu','Chuang',18,76) 23 | liu.greetr_user() 24 | -------------------------------------------------------------------------------- /python_fundamental/class_change.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue May 15 12:51:09 2018 4 | 5 | @author: lc 6 | """ 7 | 8 | class User(): 9 | """ user""" 10 | def __init__(self,first_name,last_name,age): 11 | self.first_name=first_name 12 | self.last_name=last_name 13 | self.age=age 14 | self.login_attempts=0 15 | def describe_user(self): 16 | print(self.first_name,self.age) 17 | def greetr_user(self): 18 | print(self.age) 19 | def increment_login_attempts(self,n): 20 | self.login_attempts+=n 21 | print(self.login_attempts) 22 | def reset_login_attempts(self): 23 | self.login_attempts=0 24 | liu=User('Liu','Chuang',18) 25 | liu.greetr_user() 26 | liu.increment_login_attempts(1) 27 | liu.increment_login_attempts(3) 28 | liu.reset_login_attempts() 29 | print(liu.login_attempts) 30 | -------------------------------------------------------------------------------- /python_fundamental/class_son9798.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue May 15 13:12:48 2018 4 | 5 | @author: lc 6 | 7 | 继承子类 8 | 9 | """ 10 | 11 | """ 12 | class User(): 13 | ###userkk 14 | def __init__(self,first_name,last_name,age): 15 | self.first_name=first_name 16 | self.last_name=last_name 17 | self.age=age 18 | self.login_attempts=0 19 | def describe_user(self): 20 | print(self.first_name,self.age) 21 | def greetr_user(self): 22 | print(self.age) 23 | def increment_login_attempts(self,n): 24 | self.login_attempts+=n 25 | print(self.login_attempts) 26 | def reset_login_attempts(self): 27 | self.login_attempts=0 28 | 29 | class Admin(User): 30 | def __init__(self,first_name,last_name,age):####错误太难找两个下划线 31 | super().__init__(first_name,last_name,age) 32 | self.p=["can add post","can delete post","can ban user"] 33 | def show_privileges(self): 34 | for i in self.p: 35 | print(i) 36 | liu=Admin('Liu','Chuang',20) 37 | liu.increment_login_attempts(2) 38 | liu.show_privileges() 39 | """ 40 | 41 | ###创建子类 打印权限 42 | class User(): 43 | """ user""" 44 | def __init__(self,first_name,last_name,age): 45 | self.first_name=first_name 46 | self.last_name=last_name 47 | self.age=age 48 | self.login_attempts=0 49 | def describe_user(self): 50 | print(self.first_name,self.age) 51 | def greetr_user(self): 52 | print(self.age) 53 | def increment_login_attempts(self,n): 54 | self.login_attempts+=n 55 | print(self.login_attempts) 56 | def reset_login_attempts(self): 57 | self.login_attempts=0 58 | 59 | class Show_privileges(): 60 | def __init__(self): 61 | self.p=["can add post","can delete post","can ban user"] 62 | def show_privileges(self): 63 | for i in self.p: 64 | print(i) 65 | class Admin(User): 66 | def __init__(self,first_name,last_name,age):####错误太难找两个下划线 67 | super().__init__(first_name,last_name,age) 68 | self.show=Show_privileges() 69 | 70 | 71 | -------------------------------------------------------------------------------- /python_fundamental/class_vari.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Apr 19 23:52:34 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | class Robot: 9 | 10 | population=0 11 | 12 | def __init__(self,name): 13 | self.name= name 14 | print("Initial {}".format(self.name)) 15 | Robot.population = Robot.population + 1 16 | 17 | #robert is dying 18 | def die(self): 19 | print("{} has been destroyed".format(self.name)) 20 | Robot.population -= 1 21 | if Robot.population == 0: 22 | print("{} was the last one Robert ".format(self.name)) 23 | else: 24 | print("There is still {:d} robert".format(Robot.population)) 25 | 26 | 27 | def say_hi(self): 28 | print("greetings you can call me {}".format(self.name)) 29 | 30 | #print the current population 31 | @classmethod 32 | #refre to a class variable 33 | def how_many(cls): 34 | print("we have {:d} roberts".format(cls.population)) 35 | 36 | 37 | droid1=Robot("L") 38 | droid1.say_hi() 39 | Robot.how_many() 40 | 41 | 42 | droid2=Robot("C") 43 | droid2.say_hi() 44 | Robot.how_many() 45 | 46 | droid1.die() 47 | droid2.die() 48 | Robot.how_many() 49 | 50 | 51 | -------------------------------------------------------------------------------- /python_fundamental/creat_list.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Apr 25 22:36:20 2018 4 | 5 | @author: dell 6 | """ 7 | import os 8 | 9 | 10 | A=[x+x for x in range(1,20)] 11 | 12 | B=[x+x for x in range(1,20) if x%2==0] 13 | 14 | C=[m*n for m in range(1,5) for n in range(5,10)] 15 | 16 | D=[m+n for m in 'ASDFGHJKL' for n in 'Zl'] 17 | 18 | E=[d for d in os.listdir('.')] 19 | 20 | 21 | d={'AS':12,'BS':13,'CS':14} 22 | for k,v in d.items(): 23 | print(k, '=' ,v) 24 | 25 | 26 | 27 | L = ['Hello', 'World', 'IBM', 'Apple'] 28 | F=[s.lower() for s in L] 29 | 30 | 31 | M = ['Hello', 'World', 18, 'Apple', None] 32 | G=[q.lower() for q in M if isinstance(q,str) ] 33 | 34 | print(A,B,C,D,E,F,G) 35 | -------------------------------------------------------------------------------- /python_fundamental/dict_dict.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun May 13 16:26:54 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | cities={ 9 | 'Dalian':{ 10 | 'Location':'A+', 11 | 'Environment':'A+', 12 | 'consume':'B+' 13 | }, 14 | 'Hangzhou':{ 15 | 'Location':'A', 16 | 'Environment':'A+', 17 | 'consume':'A+' 18 | }, 19 | 'Shenzhen':{ 20 | 'Location':'A', 21 | 'Environment':'A', 22 | 'consume':'A+' 23 | }, 24 | } 25 | cities['Dalian']['Location']='A-' ###??? 修改字典中的key 26 | cities['DaLian']=cities.pop('Dalian') 27 | for city,infor in cities.items(): 28 | print('\n'+city +' :') 29 | for facter,rank in infor.items(): 30 | print('\t'+facter +': '+ rank) 31 | 32 | -------------------------------------------------------------------------------- /python_fundamental/dict_list.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun May 13 15:31:19 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | 9 | 10 | #批量外星人 11 | 12 | aliens=[] 13 | for i in range(1,10): 14 | alien1={'color':'green','point':5}###不能放在for外面 15 | aliens.append(alien1) 16 | 17 | #批量修改外星人 18 | for alien in aliens[:1]: 19 | if alien['color']== 'green': 20 | alien['color']='blue' 21 | alien['point']= 2 22 | elif alien['color']=='red': 23 | alien['color']='xxx' 24 | alien['point']= 21 25 | for alien in aliens[0:6]: 26 | print(alien) 27 | 28 | 29 | -------------------------------------------------------------------------------- /python_fundamental/dict_list2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun May 13 16:09:23 2018 4 | 5 | @author: dell 6 | """ 7 | information={ 8 | 'Name':'Liu Chuang', 9 | 'Age':20, 10 | 'School':['Haiwan','37th','Wuhan University'], 11 | 'ideal':['Zhejiang','Peking'], 12 | } 13 | print('Name: '+ information['Name']+ '\n') 14 | print('Age: '+ str(information['Age'])+ '\n') 15 | print('\nSchool:') 16 | for school in information['School']: 17 | print(school) 18 | print('\nIdeal:') 19 | for ideal in information['ideal']: 20 | print(ideal) 21 | 22 | -------------------------------------------------------------------------------- /python_fundamental/fileobj_oarganisation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Jun 1 00:55:09 2018 4 | 5 | @author: 刘闯 6 | 7 | 组织文件 8 | 9 | 10 | """ 11 | 12 | """ 13 | ###1 shutil 模块 14 | 15 | ####1 复制文件和文件夹 16 | import os,shutil 17 | 18 | 19 | os.chdir('C:\\') ## 更爱当前目录 20 | shutil.copy('sourse','destination') #!!! 返回一个字符串 被复制文件的路径 21 | ### 如果 destination 是一个文件名 ,复制文件的新名字 否则 原名 22 | 23 | shutil.copytree("c:\\a","c:\\a_backup") ###复制整个文件夹 以及他包括的文件以及文件夹 24 | ### 相当于备份 a 25 | 26 | 27 | ####2 文件和文件夹的移动 28 | shutil.move('sourse','destination') 29 | ####1 des为文件夹 则文件 移入文件夹 保存原有的文件名 !!! 很可能和源文件冲突覆盖 30 | ####2 des 为文件名 则将文件移动到文件夹并且 更改名字 31 | shutil.move("C:\\bacon.txt","C:\\eggs\\new_bacon.txt") 32 | 33 | ####3 如果目录下没有文件夹 所以假定des指定的是一个文件而不是文件夹, 34 | bacon.txt ##文本文件改名为 eggs 无扩展名 35 | 36 | 37 | ####3 永久删除文件和文件夹 38 | os.unlink(path)## 删除路径的文件 39 | os.rmdir(path)## 删除路径的空文件夹 40 | os.rmtree(path) ## 删除文件夹以及其包含的所有文件和文件夹 41 | 42 | ####4 文件删除到 回收站 : send2trash 43 | import send2trash 44 | send2trash.send2trash("") 45 | 46 | 47 | ###2 遍历目录树: 处理文件夹中的每一个文件 48 | import os 49 | for folderName,subfolders,filenames in os.walk("C:\\"): 50 | print(folderName) 51 | os.walk()###返回三个值 1 当前文件夹的字符串 2 当前文件夹的子文件夹 字符串列表 3 当前文件夹的文件字符串列表 52 | """ 53 | 54 | 55 | ###3 zipfile模块 压缩 文件 56 | ####1 读取 ZIP文件 57 | import zipfile ,os 58 | os.chdir(r'C:\Users\dell\Desktop\summer_camp\LAMDA') 59 | liuzip=zipfile.ZipFile('Liu.zip') 60 | names=liuzip.namelist() 61 | for name in names: 62 | print(name.decode('utf-8'))###?如何打印中文 待解决 63 | 64 | LiuInfo=liuzip.getinfo('spam.txt') 65 | LiuInfo.file_size 66 | LiuInfo.compress_size 67 | 68 | 69 | 70 | 71 | """ 72 | import os 73 | 74 | inpath = 'G:\Android\MyAndroid\UI设计' 75 | uipath = unicode(inpath,"utf-8") ##对路径进行utf-8编码 76 | 77 | list = os.listdir(uipath) ##获得文件目录列表 78 | 79 | for each in list: ##遍历list列表 80 | print(each.encode('utf-8')) ##将该目录下文件名全部打印出来 81 | 82 | 83 | import codecs 84 | f = codecs.open('text.text','r+',encoding='utf-8')#必须事先知道文件的编码格式,这里文件编码是使用的utf-8 85 | content = f.read()#如果open时使用的encoding和文件本身的encoding不一致的话,那么这里将将会产生错误 86 | f.write('你想要写入的信息') 87 | f.close() 88 | 89 | import chardet 90 | 91 | 92 | # 获取文件编码类型 93 | def get_encoding(file): 94 | # 二进制方式读取,获取字节数据,检测类型 95 | with open(file, 'rb') as f: 96 | return chardet.detect(f.read())['encoding'] 97 | 98 | 99 | file_name = 'my.ini' 100 | encoding = get_encoding(file_name) 101 | print(encoding) 102 | """ 103 | #####2 从zip中解压缩 104 | liuzip.extractall('A') # 全部解压 可以传入一个文件夹名称 解压缩到 文件夹目录 105 | liuzip.extract('B.txt',A)## 单个解压到指定目录 106 | 107 | #####3 创建压缩文件 108 | import zipfile 109 | new_zip=zipfile.ZipFile('new.zip','w') 110 | new_zip.write('spam.txt',compress_type=zipfile.ZIP_DEALATED)##'w'写入会擦除原有内容 ‘a’添加 111 | new_zip.close() 112 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /python_fundamental/func2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon May 14 20:49:33 2018 4 | 5 | @author: lc 6 | 7 | 输入制衣 判断 无输入 或不在范围内 默认值 8 | 询问 是否按照默认值执行 9 | """ 10 | 11 | 12 | def make_shirt(size='Xl',pattern='I love you'): 13 | print("\nMy shirt is " + size.upper() +" and with a " + pattern) 14 | 15 | A=input("Which size?: ") 16 | B=input("which pattern? :") 17 | L1=['s','m','l','xl','xxl'] 18 | L2=['pig','dog','cat','panda'] 19 | if A in L1 and B in L2 : 20 | make_shirt(A,B) 21 | elif A not in L1 and B in L2 : 22 | make_shirt(pattern=B) 23 | elif A in L1 and B not in L2 : 24 | make_shirt(size=A) 25 | else: 26 | print("Sorry!! we don't have ") 27 | C=input("would you want to print by default(y/n): ") 28 | if C=='y': 29 | make_shirt() 30 | 31 | 32 | -------------------------------------------------------------------------------- /python_fundamental/func_dict87.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon May 14 21:05:28 2018 4 | 5 | @author: lc 6 | 7 | 创建一个描述音乐专辑的 字典 包含 歌手名 专辑名 歌曲数 8 | """ 9 | def make_album(singer_name,album_name,number=""): 10 | album={} 11 | album['singer_name']=singer_name 12 | album['album_name']=album_name 13 | if number : 14 | album['number']=number 15 | return album 16 | A=make_album('Li','Shanqiu',10) 17 | B=make_album('Luo','Lianqu') 18 | print(A,B) 19 | 20 | C=input('singer_name:') 21 | D=input('album_name: ') 22 | E=input('number: ') 23 | 24 | F=make_album(C,D,E) 25 | print(F) 26 | -------------------------------------------------------------------------------- /python_fundamental/func_keyfactors814.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon May 14 22:27:54 2018 4 | 5 | @author: lc 6 | 7 | 函数接受 任意关键实参 8 | """ 9 | 10 | def make_car(name,type,**infor):##**infor接受任意键值 11 | car={} 12 | car['name']=name 13 | car['type']=type 14 | for k,v in infor.items(): 15 | car[k]=v 16 | return car 17 | A=make_car('dazhong','car',color='black',size='small') 18 | print(A) 19 | -------------------------------------------------------------------------------- /python_fundamental/func_list811.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon May 14 21:49:13 2018 4 | 5 | @author: lc 6 | 7 | 函数和列表 8 | 9 | """ 10 | 11 | magicians=['Liu','Chuang','zou','xiao'] 12 | def make_great(lists): 13 | for list in lists : 14 | list='the Great '+ list # 修改列表 15 | print(list) 16 | 17 | 18 | #传递副本 19 | make_great(magicians[:]) 20 | print(magicians) 21 | -------------------------------------------------------------------------------- /python_fundamental/function_default.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Apr 17 12:50:27 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | def say(message,times=1): 9 | print(message*times) 10 | say('hello') 11 | say('gog',12) 12 | -------------------------------------------------------------------------------- /python_fundamental/function_global.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Apr 17 12:51:23 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | x = 50 9 | 10 | 11 | def func(): 12 | global x 13 | 14 | print('x is', x) 15 | x = 2 16 | print('Changed global x to', x) 17 | 18 | 19 | func() 20 | print('Value of x is', x) 21 | -------------------------------------------------------------------------------- /python_fundamental/function_return.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Apr 17 12:52:00 2018 4 | 5 | @author: dell 6 | """ 7 | import os; 8 | print(os.getcwd()) 9 | -------------------------------------------------------------------------------- /python_fundamental/input.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Apr 20 11:06:38 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | 9 | 10 | def reverse(text): 11 | return text[::-1] 12 | ''' 13 | We use the slicing feature to reverse the text. 14 | We've already seen how we can make slices from 15 | sequences using the seq[a:b] code starting from position 16 | a to position b. We can also provide a third argument that 17 | determines the step by which the slicing is done. 18 | The default step is 1 because of which it returns a continuous 19 | part of the text. Giving a negative step, i.e., -1 20 | will return the text in reverse. 21 | ''' 22 | 23 | def is_par(text): 24 | return text == reverse(text) 25 | 26 | sth=input("some text:") 27 | 28 | if is_par(sth): 29 | print("{} is par".format(sth)) 30 | else: 31 | print("{} is not par ".format(sth)) 32 | -------------------------------------------------------------------------------- /python_fundamental/map_reduce.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Apr 26 11:58:10 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | 9 | def f(x): 10 | return x*x 11 | 12 | r=list(map(f,[1,2,3,4,5,6,7])) 13 | print(r) 14 | -------------------------------------------------------------------------------- /python_fundamental/module_running_name.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Apr 18 00:18:43 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | if __name__ == '__main__': 9 | print('This program is being run by itself') 10 | else: 11 | print('I am being imported from another module') 12 | -------------------------------------------------------------------------------- /python_fundamental/module_using_sys.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Apr 18 00:06:28 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | import sys 9 | 10 | print('The command line arguments are:') 11 | for i in sys.argv: 12 | print(i) 13 | 14 | print('\n\nThe PYTHONPATH is', sys.path, '\n') 15 | -------------------------------------------------------------------------------- /python_fundamental/modules_dictionary.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Apr 18 00:02:55 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | import os; 9 | print(os.getcwd()) 10 | -------------------------------------------------------------------------------- /python_fundamental/open_write_file_prc.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed May 30 23:53:23 2018 4 | 5 | @author: 刘闯 6 | 7 | 读写文件 8 | """ 9 | 10 | ## 创建文件夹 11 | import os 12 | os.makedirs('C:\\Liu\\Chuang\\o') 13 | ###创建多层文件夹 14 | 15 | 16 | ###os.path 模块 :: 文件名和文件路径 17 | 18 | ####1 绝对路径 和相对路径 19 | os.path.abspath('.') ##'.'对应着当前路径 20 | os.path.isabs()# 判断是否为绝对路径 21 | os.path.basename('')## 文件名 22 | os.path.dirname('')## 文件路径名 23 | os.path.split('')## t同时获得 文件名和路径的元组 的 24 | 25 | 26 | ###2 查看文件和文件夹 内容 27 | 28 | os.path.getsize('') ###返回文件的字节数 29 | os.listdir('')## 返回路径下的所有文件 30 | ###利用个循环 可以计算 路径下所有文件 总字节数 31 | 32 | ###3 检查路径的有效性 33 | os.path.exists() ### 检测路径是否存在 34 | os.path.isdir('')###path 存在 并且是一个文件夹 35 | os.path.isfile('') ### path 存在 并且是一个文件 36 | 37 | 38 | ###4 读写 纯文本文件 .txt .py 39 | 40 | 41 | ###5 用 shelve 模块 保存变量 42 | import shelve 43 | shelfFile= shelve.open('mydata') 44 | Men=['Liu','Chuang','chuang'] 45 | ## 类似于字典 有keys 有values 46 | shelfFile['man']=Men 47 | shelfFile.close() 48 | 49 | ###6用 pprint.pformat() 函数保存变量 创建py 文件 50 | import pprint 51 | cats=[{'name':'Liu','Age':'16'},{'name':'Chuang','age':'12'}] 52 | fileCat=open('mycat.py','w') 53 | fileCat.write('cats =' + pprint.pformat(cats) + '\n')## pprint 返回字符串 54 | fileCat.close() 55 | 56 | ###导入python 脚本 57 | import mycat 58 | mycat.cats 59 | mycat.cats[0] 60 | ### 只有基本数据类型 整形 浮点型 字符串 列表 字典 作为简单文本写入 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /python_fundamental/prc.dict.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun May 13 12:57:43 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | favor_lan={ 9 | 'a':'py', 10 | 'b':'c+', 11 | 'c':'java', 12 | 'd':'R', 13 | } 14 | favor_lan2={ 15 | 'a':'py', 16 | 'b':'c+', 17 | 'c':'java', 18 | 'd':'R', 19 | 'e':'fortrun', 20 | 'f':'javascript', 21 | } 22 | for name in favor_lan2.keys(): 23 | if name in favor_lan.keys(): 24 | print('Thank ' + name.title() +' for intending') 25 | else: 26 | print('please ' + name.title() + ' intend') 27 | -------------------------------------------------------------------------------- /python_fundamental/prc_list2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun May 13 09:44:09 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | ##放眼世界 9 | W=['Dalian','Shanghai','Hanzhou',"xi'an",'Shenzhen'] 10 | print(W) 11 | W1=sorted(W) 12 | print('\n') 13 | print(W1) 14 | print(W) 15 | 16 | #反方向临时字符排序 17 | W2=sorted(W,reverse=True) 18 | print('\n') 19 | print(W2) 20 | print(W) 21 | 22 | #倒转列表 23 | print('\n') 24 | W.reverse() 25 | print(W) 26 | W.reverse() 27 | print(W) 28 | 29 | ##永久字母排序 30 | W.sort() 31 | print('\n') 32 | print(W) 33 | 34 | #字母反向排序 35 | W.sort(reverse=True) 36 | print(W) 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /python_fundamental/prc_list_value.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun May 13 10:26:26 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | ##列表解析 9 | A=list(range(1,20,2)) 10 | for odd in A: 11 | print(odd) 12 | print([odd for odd in range(0,20,2)]) 13 | 14 | ##3的倍数 15 | B=[] 16 | for value in range(3,30): 17 | if value%3==0: 18 | B.append(value) 19 | print(B) 20 | 21 | ##cubic 22 | print([c**3 for c in range(1,10)]) 23 | 24 | -------------------------------------------------------------------------------- /python_fundamental/subclass.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Apr 20 09:43:18 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | class SchoolMember: 9 | def __init__(self,name,age): 10 | self.name=name 11 | self.age=age 12 | print("innitialing {}".format(self.name)) 13 | 14 | def tell(self): 15 | print("Name: {} Age: {:d} ".format(self.name,self.age),end=" ") 16 | 17 | ''' 18 | The end parameter is used in 19 | the print function in the superclass's 20 | tell() method to print a line and allow the 21 | next print to continue on the same line. 22 | This is a trick to make print not print a \n (newline) symbol 23 | at the end of the printing. 24 | ''' 25 | 26 | class Teacher: 27 | def __init__(self,name,age,salary): 28 | SchoolMember.__init__(self,name,age) 29 | self.salary=salary 30 | print("innitial: {}".format(self.name)) 31 | 32 | 33 | def tell(self): 34 | SchoolMember.tell(self) 35 | print("Salary : {}".format(self.salary)) 36 | 37 | 38 | class Student: 39 | def __init__(self,name,age,mark): 40 | SchoolMember.__init__(self,name,age) 41 | self.mark=mark 42 | print("innitial: {}".format(self.name)) 43 | 44 | 45 | def tell(self): 46 | SchoolMember.tell(self) 47 | print("Mark : {}".format(self.mark)) 48 | 49 | T=Teacher("Z.X.W",20,8000) 50 | S=Student("L.C",20,90) 51 | 52 | print() 53 | 54 | members= [T,S] 55 | for member in members: 56 | member.tell() 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /python_fundamental/while_break.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun May 13 17:05:01 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | prompt="\nEnter some words upper: " 9 | prompt+="\nEnter quit if you want to quit: " 10 | message='' 11 | while message != 'quit': 12 | message=input(prompt) 13 | if message != 'quit': 14 | print(message.upper()) 15 | -------------------------------------------------------------------------------- /python_fundamental/while_breaks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon May 14 00:04:16 2018 4 | 5 | @author: dell 6 | """ 7 | 8 | prompt="\nEnter some words upper: " 9 | prompt+="\nEnter quit if you want to quit: " 10 | 11 | act=True 12 | while act : 13 | message=input(prompt) 14 | if message == 'quit': 15 | act=False 16 | elif message == 'QUIT': 17 | act=False 18 | else: 19 | print(message) 20 | 21 | -------------------------------------------------------------------------------- /python_fundamental/while_dict.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon May 14 17:38:13 2018 4 | 5 | @author: lc 6 | 7 | while 填充字典 8 | 扩展 多个人 字典添加列表 9 | """ 10 | 11 | dp={} #空储存字典 12 | place=[]#空列表 13 | p1="\nWhat is your name : " 14 | p2="\nWhere would you go : " 15 | p3="\nwhereelse would you go : " 16 | p4="\nDo you want to another(y/n) : " 17 | p5="\nAnother one(y/n)?" 18 | 19 | #设置标志位 20 | A=True 21 | while A : 22 | name=input(p1) 23 | place1=input(p2) 24 | ask=input(p4) 25 | if ask =='y': #个人列表 26 | place2=input(p3) 27 | place.append(place1) 28 | place.append(place2) 29 | dp[name]=place 30 | else: 31 | dp[name]=place1 32 | repeat=input(p5) 33 | if repeat=='n': ##多人重复 34 | A=False 35 | 36 | #打印结果 37 | print("\n ----POll list----") 38 | for k,v in dp.items(): 39 | if type(v)!=str: ##不能用len()进行判断 因为 字符列表都有长度 40 | for i in v: 41 | print(k + " would like to go to : " + i) 42 | else: 43 | print(k + " would like to go to : " + v) 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /python_fundamental/while_list.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon May 14 13:33:33 2018 4 | 5 | @author: lc 6 | 7 | 使用while 搬运列表信息 8 | 将未验证的用户运到已经验证的 9 | 订单---未完成订单 10 | 11 | while 删除列表信息 (列表很多重复信息) 12 | 13 | 14 | """ 15 | 16 | un_users=["A","B","C","D"] 17 | users=[] 18 | 19 | while un_users: 20 | in_users=un_users.pop() 21 | print(in_users + ' is joining') 22 | users.append(in_users) 23 | for user in users : 24 | print(user) 25 | print(un_users,users) 26 | 27 | #while 删除列表信息 (列表很多重复信息) 28 | pets=['A','B','C','D','A','D','F','A'] 29 | while 'A' in pets: 30 | pets.remove('A') 31 | print(pets) 32 | -------------------------------------------------------------------------------- /python_lib/Matplotlib/README.md: -------------------------------------------------------------------------------- 1 | # 1 2 | 3 | ### 1. plt.sca() 4 | 5 | > subplot()返回它所创建的Axes对象,我们可以将它用变量保存起来,然后用sca()交替让它们成为当前Axes对象,并调用plot()在其中绘图。 6 | 7 | 8 | ```python 9 | 10 | plt.figure(1) # 创建图表1 11 | plt.figure(2) # 创建图表2 12 | ax1 = plt.subplot(211) # 在图表2中创建子图1 13 | ax2 = plt.subplot(212) # 在图表2中创建子图2 14 | 15 | x = np.linspace(0, 3, 100) 16 | for i in xrange(5): 17 | plt.figure(1) #❶ # 选择图表1 18 | plt.plot(x, np.exp(i*x/3)) 19 | plt.sca(ax1) #❷ # 选择图表2的子图1 20 | plt.plot(x, np.sin(i*x)) 21 | plt.sca(ax2) # 选择图表2的子图2 22 | plt.plot(x, np.cos(i*x)) 23 | 24 | ``` 25 | 26 | 27 | ### 2. ply.gca() 28 | 29 | > 使用plt.gca获取当前坐标轴信息. 30 | 31 | ```python 32 | 33 | axes = plt.gca() 34 | axes.set_xlim([x_min,x_max]) 35 | axes.set_ylim([y_min,y_max]) 36 | axes.set(xlabel="$X_1$", ylabel="$X_2$") 37 | 38 | ``` 39 | 40 | 41 | ### 3. plt.contour([X, Y,] Z, [levels], **kwargs) --绘制等高线 无颜色填充 42 | * X, Y : array-like, optional;The coordinates of the values in Z.X and Y must both be 2-D with the same shape as Z (e.g. created via numpy.meshgrid()), 43 | 44 | * Z : array-like(N, M) .The height values over which the contour is drawn. 45 | 46 | 47 | ### 4. plt.contourf([X, Y,] Z, [levels], **kwargs) -- 颜色填充 48 | 49 | 50 | 51 | 52 | 53 | ### 5. plt.scatter 54 | ```python 55 | plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train.ravel(), s=50, cmap=plt.cm.Spectral, edgecolors='black'); 56 | 57 | ``` 58 | * c: 点的颜色 接收A sequence of n numbers to be mapped to colors using cmap and norm. 转换y 的格式 59 | * s: 表示 x点的大小 ,可以表示为x的函数 60 | * edgecolors : 边框颜色 61 | * cmap = plt.cm.Spectral实现的功能是给label为1的点一种颜色,给label为0的点另一种颜色。 可以 自定义颜色 62 | 63 | 64 | ```python 65 | C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5) 66 | # 等高线,8 代表分成8个部分。线款 67 | plt.clabel(C, inline=True, fontsize=10) 68 | # 绘制高度数字 69 | ``` 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /python_lib/Numpy/README.md: -------------------------------------------------------------------------------- 1 | # numpy 学习 2 | 3 | 4 | 5 | 6 | ## 1 内存结构 7 | 8 | ![](http://old.sebug.net/paper/books/scipydoc/_images/numpy_memory_struct.png) 9 | 10 | ```python 11 | a = np.array([[0,1,2],[3,4,5],[6,7,8]], dtype=np.float32) 12 | ``` 13 | 14 | 15 | > strides中保存的是当每个轴的下标增加1时,数据存储区中的指针所增加的字节数。例如图中的strides为12,4,即第0轴的下标增加1时,数据的地址增加12个字节:即a[1,0]的地址比a[0,0]的地址要高12个字节,正好是3个单精度浮点数的总字节数;第1轴下标增加1时,数据的地址增加4个字节,正好是单精度浮点数的字节数。 16 | > 17 | > 如果strides中的数值正好和对应轴所占据的字节数相同的话,那么数据在内存中是连续存储的。然而数据并不一定都是连续储存的 18 | 19 | 20 | ## 2 ufunc 21 | * func是universal function的缩写,它是一种能对数组的每个元素进行操作的函数。NumPy内置的许多ufunc函数都是在C语言级别实现的,因此它们的计算速度非常快。 22 | 23 | 24 | ```python 25 | 26 | import numpy as np 27 | 28 | 29 | x = np.linspace(0,2*np.pi,10) 30 | 31 | y=np.sin(x) 32 | ###它对x中的每个元素求正弦值,然后将结果返回,并且赋值给y。 33 | ###计算之后x中的值并没有改变,而是新创建了一个数组保存结果 34 | 35 | print(y) 36 | 37 | ``` 38 | 39 | * y = x1 + x2: add(x1, x2 [, y]) 40 | 41 | * y = x1 - x2: subtract(x1, x2 [, y]) 42 | 43 | * y = x1 * x2: multiply (x1, x2 [, y]) 44 | 45 | * y = x1 / x2: divide (x1, x2 [, y]), 如果两个数组的元素为整数,那么用整数除法 46 | 47 | * y = x1 / x2: true divide (x1, x2 [, y]), 总是返回精确的商 48 | 49 | * y = x1 // x2: floor divide (x1, x2 [, y]), 总是对返回值取整 50 | 51 | * y = -x: negative(x [,y]) 52 | 53 | * y = x1**x2: power(x1, x2 [, y]) 54 | 55 | * y = x1 % x2: remainder(x1, x2 [, y]), mod(x1, x2, [, y]) 56 | 57 | ------ 58 | 数组对象支持这些操作符,极大地简化了算式的编写,不过要注意如果你的算式很复杂,并且要运算的数组很大的话,会因为产生大量的中间结果而降低程序的运算效率。例如:假设a b c三个数组采用算式x=a*b+c计算,那么它相当于: 59 | 60 | ----- 61 | 62 | ```python 63 | t = a * b 64 | x = t + c 65 | del t 66 | # 也就是说需要产生一个数组t保存乘法的计算结果,然后再产生最后的结果数组x。我们可以通过手工将一个算式分解为x = a*b; x += c,以减少一次内存分配。 67 | ``` 68 | 69 | 70 | ------------ 71 | 72 | ## 3 保存 73 | 74 | ### 1 通过下标范围产生数组 和原数组共享数据空间 75 | ```python 76 | b=a[::-1] ## 步长为负数 倒序 77 | c=a[3:7] ### 左开右闭 78 | ``` 79 | 80 | ### 2 通过整数序列 元素选取 每个元素作为下标 获得新数组 不共享空间 81 | ```python 82 | d=a[[1,2,3,5]] 83 | a[[1,2,3]]=4,5,6 84 | 85 | 86 | print(a,b,c,d) 87 | 88 | ``` 89 | ### 3 布尔数组 90 | 91 | ```python 92 | e = np.arange(3) 93 | f=e[np.array([True,False,True])] 94 | print('\n\n') 95 | print(f) 96 | 97 | ``` 98 | -------- 99 | -------- 100 | 101 | ## 4. arrange 102 | 103 | 1. np.arrange --numpy.arange([start, ]stop, [step, ]dtype=None) : 每步分割的大小 104 | 105 | > Values are generated within the half-open interval [start, stop) 106 | 107 | ```python 108 | 109 | >>> np.arange(3) 110 | array([0, 1, 2]) 111 | >>> np.arange(3.0) 112 | array([ 0., 1., 2.]) 113 | >>> np.arange(3,7) 114 | array([3, 4, 5, 6]) 115 | >>> np.arange(3,7,2) 116 | array([3, 5]) 117 | 118 | ``` 119 | 120 | 121 | ----- 122 | 123 | 124 | 2. numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) 125 | 126 | * endpoint : 是否包含 stop 值, 不过 总数 num 不变 127 | 128 | * retstep : 给出 步长 If True, return (samples, step) 129 | 130 | ```python 131 | >>> np.linspace(2.0, 3.0, num=5) 132 | array([ 2. , 2.25, 2.5 , 2.75, 3. ]) 133 | >>> np.linspace(2.0, 3.0, num=5, endpoint=False) 134 | array([ 2. , 2.2, 2.4, 2.6, 2.8]) 135 | >>> np.linspace(2.0, 3.0, num=5, retstep=True) 136 | (array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25 137 | 138 | ``` 139 | 140 | ----- 141 | 142 | 3. np.meshgrid 143 | 144 | 145 | ```python 146 | nx, ny = (3, 2) 147 | >>> x = np.linspace(0, 1, nx) 148 | >>> y = np.linspace(0, 1, ny) 149 | >>> xv, yv = np.meshgrid(x, y) 150 | >>> xv 151 | array([[ 0. , 0.5, 1. ], 152 | [ 0. , 0.5, 1. ]]) 153 | >>> yv 154 | array([[ 0., 0., 0.], 155 | [ 1., 1., 1.]]) 156 | 157 | ``` 158 | 159 | 160 | * size(x) = 3 理解为坐标轴的x ---对应的 矩阵的列。, 相当于 坐标轴上的一条条横线; size(y) = 2 理解为坐标轴 的y。 对应矩阵的 row; 相当于 坐标轴上一列列竖线 161 | 162 | * 二者 均需 broadcast 到相应的行数 和列数 163 | 164 | 165 | * xv yv 矩阵 坐标数相同的点 ,共同表示 坐标轴内的 一个点。例如 x0y0 = (0,0) ;x0y1 = (0,1) 166 | 167 | 168 | **Meshgrid函数常用的场景有等高线绘制及机器学习中SVC超平面的绘制** 169 | 170 | 171 | 172 | 173 | --- 174 | 175 | ## 5. 176 | 177 | * np.r_是按列连接两个矩阵,就是把两矩阵上下相加,要求列数相等,类似于pandas中的concat()。 178 | * np.c_是按行连接两个矩阵,就是把两矩阵左右相加,要求行数相等,类似于pandas中的merge()。 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | -------------------------------------------------------------------------------- /python_lib/Numpy/numpy_array.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Jun 12 00:50:33 2018 5 | 6 | @author: liuchuang 7 | """ 8 | import numpy as np 9 | 10 | 11 | 12 | a= np.array([1,2,3])## 一位数组 13 | print(type(a)) 14 | print(a.shape) ###数组大小 15 | print(a[0]) 16 | 17 | a[0]=5 18 | print(a) 19 | 20 | 21 | b=np.array([[1,2,3],[4,5,6]]) ##二维数组 22 | print(b.shape) 23 | print(b[0,1],b[1,1]) 24 | print(b) 25 | 26 | print('\n\n' ) 27 | 28 | c=np.zeros((2,2)) 29 | print(c) 30 | print('\n') 31 | 32 | d=np.ones((1,2)) 33 | print(d) 34 | print('\n') 35 | 36 | 37 | e=np.full((3,3),7) 38 | print(e) 39 | print('\n') 40 | 41 | f =np.eye(2) 42 | print(f) 43 | print('\n') 44 | 45 | 46 | g=np.random.random((2,2)) 47 | print(e) 48 | 49 | 50 | h=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) 51 | 52 | #use slicing to pull out subarray 53 | 54 | k=h[:2,1:3] 55 | 56 | 57 | 58 | h.shape=4,3 59 | h.shape=2,-1### -1 时自动计算轴的长度 60 | 61 | l=h.reshape((6,2))##数组l,h 共享数据储存内存区域 62 | print(l) 63 | 64 | 65 | 66 | 67 | print(h) 68 | print('\n\n') 69 | 70 | print(k) 71 | 72 | 73 | ####???? 74 | row_r1 = h[1, :] # Rank 1 view of the second row of a 75 | row_r2 = h[1:2, :] # Rank 2 view of the second row of a 76 | print(row_r1, row_r1.shape) # Prints "[5 6 7 8] (4,)" 77 | print(row_r2, row_r2.shape) # Prints "[[5 6 7 8]] (1, 4)" 78 | 79 | # We can make the same distinction when accessing columns of an array: 80 | col_r1 = h[:, 1] 81 | col_r2 = h[:, 1:2] 82 | print(col_r1, col_r1.shape) # Prints "[ 2 6 10] (3,)" 83 | print(col_r2, col_r2.shape) 84 | 85 | 86 | 87 | 88 | ### 数组的元素类型 89 | 90 | array_type=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]],dtype=np.float) 91 | 92 | print(array_type) 93 | 94 | array_type2=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]],dtype=np.complex) 95 | print(array_type2) 96 | 97 | 98 | ### 创建数组的元素 99 | 100 | #### 1 arange ===range (开始,终止 ,步长) 101 | array1 = np.arange(0,1,0.1) 102 | print(array1) 103 | 104 | 105 | #### 2 linespace (开始,终止,元素个数)默认包含终止值(endpoint) 106 | array2 = np.linspace(0,1,10) 107 | print(array2) 108 | 109 | 110 | #### 3 logspace 等比 111 | array3 = np.logspace(0,3,33) 112 | print(array3) 113 | 114 | 115 | ### 字节序列创建数组 116 | s = "abcdefgh" 117 | 118 | 119 | #### 1 字符串为字节序列,每个字符占一个字节 120 | s_int8 = np.fromstring(s,dtype = np.int8) 121 | 122 | #### 2 16bit 两个相邻字节为一个整数 123 | s_int16 = np.fromstring(s,dtype = np.int16) 124 | 125 | #### 3 64位 双精度浮点数数组 126 | s_float = np.fromstring(s, dtype = np.float) 127 | 128 | 129 | print(s_int8,s_int16,s_float) 130 | 131 | 132 | ### 二维数组创建乘法表 133 | def func(i,j): 134 | return (i+1)*(j+1) 135 | 136 | a = np.fromfunction(func,(9,9)) 137 | ### 第一个参数 为计算每个数组元素的函数,, 138 | ### 第二个参数 序列 数组大小 139 | 140 | print(a) 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | -------------------------------------------------------------------------------- /python_lib/Numpy/numpy_save_use.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 13 00:14:35 2018 5 | 6 | @author: liuchuang 7 | """ 8 | 9 | 10 | import numpy as np 11 | 12 | 13 | a = np.arange(10) 14 | 15 | ### 1 通过下标范围产生数组 和原数组共享数据空间 16 | b=a[::-1] ## 步长为负数 倒序 17 | c=a[3:7] ### 左开右闭 18 | 19 | 20 | ### 2 通过整数序列 元素选取 每个元素作为下标 获得新数组 不共享空间 21 | 22 | d=a[[1,2,3,5]] 23 | a[[1,2,3]]=4,5,6 24 | 25 | 26 | print(a,b,c,d) 27 | 28 | 29 | ### 3 布尔数组 30 | 31 | e = np.arange(3) 32 | f=e[np.array([True,False,True])] 33 | print('\n\n') 34 | print(f) -------------------------------------------------------------------------------- /python_lib/Numpy/numpy_ufunc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 13 00:46:16 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | ufunc是universal function的缩写, 10 | 它是一种能对数组的每个元素进行操作的函数。 11 | NumPy内置的许多ufunc函数都是在C语言级别实现的, 12 | 因此它们的计算速度非常快。 13 | """ 14 | 15 | import numpy as np 16 | 17 | 18 | x = np.linspace(0,2*np.pi,10) 19 | 20 | y=np.sin(x) 21 | ###它对x中的每个元素求正弦值,然后将结果返回,并且赋值给y。 22 | ###计算之后x中的值并没有改变,而是新创建了一个数组保存结果 23 | ## 24 | print(y) 25 | 26 | 27 | -------------------------------------------------------------------------------- /python_lib/Numpy/numpy_weave.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 13 13:26:00 2018 5 | 6 | @author: liuchuang 7 | """ 8 | 9 | import scipy.weave as weave 10 | import numpy as np 11 | import time 12 | 13 | def my_sum(a): 14 | n=int(len(a)) 15 | code=""" 16 | int i; 17 | 18 | double counter; 19 | counter =0; 20 | for(i=0;i 0: 31 | pg.dragRel(distance,0,duration=0.2) 32 | distance = distance -5 33 | pg.dragRel(0,distance,duration=0.2) 34 | pg.dragRel(-distance,0,duration=0.2) 35 | distance = distance - 5 36 | pg.dragRel(0,-distance,duration=0.2) 37 | 38 | 39 | ### 3 窗口滚动 40 | 41 | pg.scroll(100) ## + :up - : down 42 | 43 | -------------------------------------------------------------------------------- /python_lib/PyAutoGui/move_pyautogui.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jun 27 00:04:39 2018 5 | 6 | @author: liuchuang 7 | 8 | 控制鼠标移动 9 | """ 10 | import pyautogui 11 | 12 | 13 | ### 1 移动鼠标 14 | for i in range(10): 15 | pyautogui.moveTo(100,100,duration=1.0)###移动到指定的像素点 16 | pyautogui.moveTo(150,200,duration=1.0) 17 | pyautogui.moveTo(250,100,duration=1.0) 18 | 19 | 20 | for i in range(10): 21 | pyautogui.moveRel(1000,0,duration=0.25) ### 移动多少像素点 22 | pyautogui.moveRel(0,800,duration=0.25) 23 | pyautogui.moveRel(-1000,0,duration=0.25) 24 | pyautogui.moveRel(0,-800,duration=0.25) 25 | 26 | 27 | ### 2 获取鼠标位置 28 | 29 | a=pyautogui.position() ##返回鼠标位置元祖 30 | -------------------------------------------------------------------------------- /python_lib/PyAutoGui/screen_pyautogui.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Jun 28 16:21:49 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 图像识别 10 | 11 | """ 12 | 13 | 14 | import pyautogui 15 | 16 | 17 | a=pyautogui.locateOnScreen('symbol5.png') 18 | 19 | 20 | print(a) 21 | 22 | b=pyautogui.center(a) 23 | 24 | print(b) 25 | 26 | pyautogui.doubleClick(b) 27 | -------------------------------------------------------------------------------- /python_lib/PyAutoGui/screenshot_pyautogui.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Jun 28 15:55:56 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | 屏幕处理 10 | 11 | """ 12 | 13 | 14 | import pyautogui 15 | 16 | im = pyautogui.screenshot() ### im 返回一个image 图像 可以 使用pillow 处理 17 | 18 | print(im.getpixel((2,3))) ## 传入一个元组 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /python_lib/Time/README.md: -------------------------------------------------------------------------------- 1 | # python--time模块学习 2 | 3 | 4 | ## 3 Time access and conversions 5 | - [时间](https://docs.python.org/3/library/time.html#time.strftime) 6 | - [时间模块](https://mp.weixin.qq.com/s/9ti4QNsTqhjDNbaF2NQAlg) 7 | -------------------------------------------------------------------------------- /python_lib/Time/datetime.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sun Jul 15 01:25:13 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | datetime module 10 | 11 | """ 12 | 13 | import datetime 14 | import time 15 | 16 | ## 1 datetime 数据类型 17 | 18 | 19 | dt = datetime.datetime.now() ## 返回一个 datetime 对象 20 | 21 | dt1 = datetime.datetime(2018,7,15,1,37,0) ##传入数据 22 | 23 | print(dt1.year,dt1.month,dt1.day) 24 | 25 | print(dt1.second) 26 | 27 | # datetime 对象可以进行比较 28 | 29 | datetime.datetime.fromtimestamp(time.time())# Unix 纪元时间 转换为本地时间 30 | 31 | ## 2 tiemdelta 数据类型 : 表示一段时间 32 | 33 | delta = datetime.timedelta(days=3,hours=4,minutes=4,seconds=4) 34 | #datetime.timedelta()函数 接受关键字参数 weeks、days、hours、minutes、seconds、milliseconds 和 microseconds 35 | 36 | print(delta.seconds) # 不包括天数的总秒数 37 | print(delta.total_seconds()) ## 包括天数的 总秒数 38 | print(str(delta)) ## 返回格式良好的 时间 39 | 40 | 41 | ## 3 datetime 和dtime delta 进行日期计算 42 | 43 | dt2= datetime.datetime.now() 44 | delta2 = datetime.timedelta(days = 1000) 45 | print(dt2 + delta2) ## 计算10000 天之后的日期 46 | 47 | ## 4 time.sleep() datetime 暂停到特定的时间 48 | """ 49 | dt3 = datetime.datetime(2018,7,18,0,0,0) 50 | while datetime.datetime() < dt3: 51 | time.sleep(1) 52 | """ 53 | 54 | ## 5 datetime 对象 和字符串相互转化 55 | ### 1 datetime 转换字符串 56 | 57 | today = datetime.datetime(2018,7,15,2,9,8) 58 | print(today.strftime('%Y%m%d')) 59 | print(today.strftime('%I:%M,%p')) 60 | 61 | 62 | ### 2 字符串 转换为 datetime 63 | 64 | datetime.datetime.strptime('October 21, 2015', '%B %d, %Y')# 类似于正则变换 65 | 66 | datetime.datetime.strptime('2015/10/21 16:29:00', '%Y/%m/%d %H:%M:%S') # 准确匹配 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /python_lib/Time/time_round.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sun Jul 15 00:44:12 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | round() 10 | 11 | function 四舍五入 12 | 13 | 传入两个 一个 为需要修改的小数 14 | 一个为需要保留的位数( 默认值为0) 15 | 16 | 17 | 18 | """ 19 | 20 | import time 21 | 22 | now = time.time() 23 | 24 | time1 = round(now) ## 保留到整数 25 | 26 | time2 = round(now,3) ### 保留小数点后 n位 小数 27 | 28 | print(str(time1)+ '\n'+str(time2)) -------------------------------------------------------------------------------- /python_lib/Time/time_sleep.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sun Jul 15 00:39:04 2018 5 | 6 | @author: liuchuang 7 | 8 | 9 | time.sleep function 10 | 11 | 如果需要让程序暂停一下,就调用 time.sleep()函数,并传入希望程序暂停的秒 12 | """ 13 | 14 | import time 15 | 16 | for i in range(3): 17 | print("I") 18 | time.sleep(2) 19 | print("Love") 20 | time.sleep(2) 21 | print("You") 22 | time.sleep(2) 23 | 24 | -------------------------------------------------------------------------------- /python_lib/Time/time_time.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sun Jul 15 00:06:09 2018 5 | 6 | @author: liuchuang 7 | 8 | time 模块学习 9 | 10 | """ 11 | 12 | import time 13 | 14 | ## 1 time.time() function 15 | 16 | 17 | print(time.time()) 18 | #返回值是 Unix 纪元的那一刻与 time.time()被调用的那一刻之间的秒数 19 | 20 | ### 1 测量一段代码运行的时间 21 | 22 | 23 | def test1(): 24 | number = 1 25 | 26 | for i in range(1,100000): 27 | number = number * i 28 | 29 | return number 30 | 31 | starttime= time.time() 32 | num=test1() 33 | endtime = time.time() 34 | costtime = endtime - starttime 35 | 36 | print("costtime:%s" %costtime) 37 | print(len(str(num))) -------------------------------------------------------------------------------- /python_lib/Typing/README.md: -------------------------------------------------------------------------------- 1 | # Typing 模块学习 2 | 3 | # 1. 简介 4 | 5 | * python增加类型暗示 : 函数变量声明为一种特定的类型。 6 | 7 | * 仅仅是暗示 而不是绑定,不能组织传入不应该传入的数据 8 | 9 | # 2. 使用 10 | 11 | ## 1. 基本使用 12 | 13 | https://github.com/LiuChuang0059/python_practise/blob/master/python-Typing/python-typing.ipynb 14 | 15 | * 参考:作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 16 | -------------------------------------------------------------------------------- /python_lib/Typing/python-typing.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 1. typing 基本使用" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "name": "stdout", 17 | "output_type": "stream", 18 | "text": [ 19 | "Mike entered 13\n" 20 | ] 21 | } 22 | ], 23 | "source": [ 24 | "import typing\n", 25 | "def some_function(number:int,name:str) -> None:\n", 26 | " print(\"%s entered %s\"%(name,number))\n", 27 | " \n", 28 | "some_function(13,\"Mike\")" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "* 函数的第一个变量是整数,第二个变量是字符串,函数返回NOne" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 3, 41 | "metadata": {}, 42 | "outputs": [ 43 | { 44 | "name": "stdout", 45 | "output_type": "stream", 46 | "text": [ 47 | "True\n", 48 | "False\n" 49 | ] 50 | } 51 | ], 52 | "source": [ 53 | "def process_data(my_list:list,name:str) -> bool:\n", 54 | " return name in my_list\n", 55 | "\n", 56 | "if __name__ == \"__main__\":\n", 57 | " my_list = [\"Mike\",\"Nick\",\"Toby\"]\n", 58 | " print(process_data(my_list,\"Mike\"))\n", 59 | " print(process_data(my_list,\"John\"))" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "# 2. 类型暗示包括 : 内置的类,抽象出的基本类,types模块的类型和用户定义的类型。\n" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "metadata": {}, 72 | "source": [ 73 | "### 1. 自定义类的暗示" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": 13, 79 | "metadata": {}, 80 | "outputs": [ 81 | { 82 | "name": "stdout", 83 | "output_type": "stream", 84 | "text": [ 85 | "orange\n", 86 | "apple\n", 87 | "['orange', 'apple']\n" 88 | ] 89 | } 90 | ], 91 | "source": [ 92 | "class Fruit:\n", 93 | " def __init__(self,name,color):\n", 94 | " self.name = name\n", 95 | " self.color = color\n", 96 | "\n", 97 | "def salad(fruit_one:Fruit,fruit_two:Fruit) -> list:\n", 98 | " #print (fruit_one.name)\n", 99 | " #print (fruit_two.name)\n", 100 | " \n", 101 | " return [fruit_one.name, fruit_two.name]\n", 102 | "\n", 103 | "if __name__ == \"__main__\":\n", 104 | " f1 = Fruit(\"orange\",\"orange\")\n", 105 | " f2 = Fruit(\"apple\",\"red\")\n", 106 | " list2= salad(f1,f2)\n", 107 | " for i in list2:\n", 108 | " print(i)\n", 109 | " print(list2)" 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "metadata": {}, 115 | "source": [ 116 | "### 2. 创建别名\n" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": 15, 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [ 125 | "import string" 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": 16, 131 | "metadata": {}, 132 | "outputs": [ 133 | { 134 | "name": "stdout", 135 | "output_type": "stream", 136 | "text": [ 137 | "The zoo has 10 Zebras\n" 138 | ] 139 | } 140 | ], 141 | "source": [ 142 | "Animal = string\n", 143 | "\n", 144 | "def zoo(animal:Animal,number:int) -> None:\n", 145 | " print(\"The zoo has %s %s\" % (number,animal))\n", 146 | "\n", 147 | "if __name__ == \"__main__\":\n", 148 | " zoo(\"Zebras\",10)\n", 149 | " " 150 | ] 151 | }, 152 | { 153 | "cell_type": "markdown", 154 | "metadata": {}, 155 | "source": [ 156 | "* 将变量Animal作为string类型的别名。然后我们使用别名Animal向我们的函数添加一个暗示。" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [] 165 | } 166 | ], 167 | "metadata": { 168 | "kernelspec": { 169 | "display_name": "Python 3", 170 | "language": "python", 171 | "name": "python3" 172 | }, 173 | "language_info": { 174 | "codemirror_mode": { 175 | "name": "ipython", 176 | "version": 3 177 | }, 178 | "file_extension": ".py", 179 | "mimetype": "text/x-python", 180 | "name": "python", 181 | "nbconvert_exporter": "python", 182 | "pygments_lexer": "ipython3", 183 | "version": "3.6.5" 184 | } 185 | }, 186 | "nbformat": 4, 187 | "nbformat_minor": 2 188 | } 189 | --------------------------------------------------------------------------------