python学习笔记_week28

 

heap
 1 import heapq
 2 import random
 3 heap = []
 4 data = list(range(10000))
 5 random.shuffle(data)
 6 # for num in data:
 7 #     heapq.heappush(heap, num)
 8 # for i in range(len(heap)):
 9 #     print(heapq.heappop(heap))
10 print(heapq.nsmallest(10, data))
View Code
linklist
 1 class Node(object):
 2     def __init__(self, item=None):
 3         self.item = item
 4         self.next = None
 5 head = Node()
 6 head.next = Node(20)
 7 head.next.next = Node(30)
 8 def traversal(head):
 9     curNode = head  # 临时用指针
10     while curNode is not None:
11         print(curNode.item)
12         curNode = curNode.next
13 traversal(head)
View Code
maze
 1 maze = [
 2     [1,1,1,1,1,1,1,1,1,1],
 3     [1,0,0,1,0,0,0,1,0,1],
 4     [1,0,0,1,0,0,0,1,0,1],
 5     [1,0,0,0,0,1,1,0,0,1],
 6     [1,0,1,1,1,0,0,0,0,1],
 7     [1,0,0,0,1,0,0,0,0,1],
 8     [1,0,1,0,0,0,1,0,0,1],
 9     [1,0,1,1,1,0,1,1,0,1],
10     [1,1,0,0,0,0,0,1,0,1],
11     [1,1,1,1,1,1,1,1,1,1]
12 ]
13 dirs = [lambda x, y: (x + 1, y),
14         lambda x, y: (x - 1, y),
15         lambda x, y: (x, y - 1),
16         lambda x, y: (x, y + 1)]
17 
18 def mpath(x1, y1, x2, y2):
19     stack = []
20     stack.append((x1, y1))
21     while len(stack) > 0:
22         curNode = stack[-1]
23         if curNode[0] == x2 and curNode[1] == y2:
24             #到达终点
25             for p in stack:
26                 print(p)
27             return True
28         for dir in dirs:
29             nextNode = dir(curNode[0], curNode[1])
30             if maze[nextNode[0]][nextNode[1]] == 0:
31                 #找到了下一个
32                 stack.append(nextNode)
33                 maze[nextNode[0]][nextNode[1]] = -1  # 标记为已经走过,防止死循环
34                 break
35         else:#四个方向都没找到
36             maze[curNode[0]][curNode[1]] = -1  # 死路一条,下次别走了
37             stack.pop() #回溯
38     print("没有路")
39     return False
40 mpath(1,1,8,8)
View Code
q_maze
 1 from collections import  deque
 2 mg = [
 3     [1,1,1,1,1,1,1,1,1,1],
 4     [1,0,0,1,0,0,0,1,0,1],
 5     [1,0,0,1,0,0,0,1,0,1],
 6     [1,0,0,0,0,1,1,0,0,1],
 7     [1,0,1,1,1,0,0,0,0,1],
 8     [1,0,0,0,1,0,0,0,0,1],
 9     [1,0,1,0,0,0,1,0,0,1],
10     [1,0,1,1,1,0,1,1,0,1],
11     [1,1,0,0,0,0,0,1,0,1],
12     [1,1,1,1,1,1,1,1,1,1]
13 ]
14 dirs = [lambda x, y: (x + 1, y),
15         lambda x, y: (x - 1, y),
16         lambda x, y: (x, y - 1),
17         lambda x, y: (x, y + 1)]
18 
19 def print_p(path):
20     curNode = path[-1]
21     realpath = []
22     print('迷宫路径为:')
23     while curNode[2] != -1:
24         realpath.append(curNode[0:2])
25         curNode = path[curNode[2]]
26     realpath.append(curNode[0:2])
27     realpath.reverse()
28     print(realpath)
29 def mgpath(x1, y1, x2, y2):
30     queue = deque()
31     path = []
32     queue.append((x1, y1, -1))
33     while len(queue) > 0:
34         curNode = queue.popleft()
35         path.append(curNode)
36         if curNode[0] == x2 and curNode[1] == y2:
37             #到达终点
38             print_p(path)
39             return True
40         for dir in dirs:
41             nextNode = dir(curNode[0], curNode[1])
42             if mg[nextNode[0]][nextNode[1]] == 0:  # 找到下一个方块
43                 queue.append((*nextNode, len(path) - 1))
44                 mg[nextNode[0]][nextNode[1]] = -1  # 标记为已经走过
45     return False
46 mgpath(1,1,8,8)
View Code
queue
1 from collections import deque
2 queue = deque()
3 queue.append(1)
4 queue.append(2)
5 print(queue.popleft())
View Code
search
 1 import time
 2 import random
 3 def cal_time(func):
 4     def wrapper(*args, **kwargs):
 5         t1 = time.time()
 6         result = func(*args, **kwargs)
 7         t2 = time.time()
 8         print("%s running time: %s secs." % (func.__name__, t2 - t1))
 9         return result
10     return wrapper
11 @cal_time
12 def bin_search(data_set, val):
13     low = 0
14     high = len(data_set) - 1
15     while low <= high:
16         mid = (low+high)//2
17         if data_set[mid] == val:
18             return mid
19         elif data_set[mid] < val:
20             low = mid + 1
21         else:
22             high = mid - 1
23     return
24 def binary_search(dataset, find_num):
25     if len(dataset) > 1:
26         mid = int(len(dataset) / 2)
27         if dataset[mid] == find_num:
28             #print("Find it")
29             return dataset[mid]
30         elif dataset[mid] > find_num:
31             return binary_search(dataset[0:mid], find_num)
32         else:
33             return binary_search(dataset[mid + 1:], find_num)
34     else:
35         if dataset[0] == find_num:
36             #print("Find it")
37             return dataset[0]
38         else:
39             pass
40             #print("Cannot find it.")
41 @cal_time
42 def binary_search_alex(data_set, val):
43     return binary_search(data_set, val)
44 def random_list(n):
45     result = []
46     ids = list(range(1001,1001+n))
47     a1 = ['zhao','qian','sun','li']
48     a2 = ['li','hao','','']
49     a3 = ['qiang','guo']
50     for i in range(n):
51         age = random.randint(18,60)
52         id = ids[i]
53         name = random.choice(a1)+random.choice(a2)+random.choice(a3)
54 data = list(range(100000))
55 print(bin_search(data, 90))
56 print(binary_search_alex(data, 90))
View Code
sort
  1 import random
  2 import time
  3 import copy
  4 import sys
  5 def cal_time(func):
  6     def wrapper(*args, **kwargs):
  7         t1 = time.time()
  8         result = func(*args, **kwargs)
  9         t2 = time.time()
 10         print("%s running time: %s secs." % (func.__name__, t2 - t1))
 11         return result
 12     return wrapper
 13 @cal_time
 14 def bubble_sort(li):
 15     for i in range(len(li) - 1):
 16         for j in range(len(li) - i - 1):
 17             if li[j] > li[j+1]:
 18                 li[j], li[j+1] = li[j+1], li[j]
 19 @cal_time
 20 def bubble_sort_1(li):
 21     for i in range(len(li) - 1):
 22         exchange = False
 23         for j in range(len(li) - i - 1):
 24             if li[j] > li[j+1]:
 25                 li[j], li[j+1] = li[j+1], li[j]
 26                 exchange = True
 27         if not exchange:
 28             break
 29 def select_sort(li):
 30     for i in range(len(li) - 1):
 31         min_loc = i
 32         for j in range(i+1,len(li)):
 33             if li[j] < li[min_loc]:
 34                 min_loc = j
 35         li[i], li[min_loc] = li[min_loc], li[i]
 36 def insert_sort(li):
 37     for i in range(1, len(li)):
 38         tmp = li[i]
 39         j = i - 1
 40         while j >= 0 and li[j] > tmp:
 41             li[j+1]=li[j]
 42             j = j - 1
 43         li[j + 1] = tmp
 44 def quick_sort_x(data, left, right):
 45     if left < right:
 46         mid = partition(data, left, right)
 47         quick_sort_x(data, left, mid - 1)
 48         quick_sort_x(data, mid + 1, right)
 49 def partition(data, left, right):
 50     tmp = data[left]
 51     while left < right:
 52         while left < right and data[right] >= tmp:
 53             right -= 1
 54         data[left] = data[right]
 55         while left < right and data[left] <= tmp:
 56             left += 1
 57         data[right] = data[left]
 58     data[left] = tmp
 59     return left
 60 @cal_time
 61 def quick_sort(data):
 62     return quick_sort_x(data, 0, len(data) - 1)
 63 @cal_time
 64 def sys_sort(data):
 65     return data.sort()
 66 def sift(data, low, high):
 67     i = low
 68     j = 2 * i + 1
 69     tmp = data[i]
 70     while j <= high:    #孩子在堆里
 71         if j + 1 <= high and data[j] < data[j+1]:   #如果有右孩子且比左孩子大
 72             j += 1  #j指向右孩子
 73         if data[j] > tmp:   #孩子比最高领导大
 74             data[i] = data[j]   #孩子填到父亲的空位上
 75             i = j               #孩子成为新父亲
 76             j = 2 * i +1        #新孩子
 77         else:
 78             break
 79     data[i] = tmp           #最高领导放到父亲位置
 80 @cal_time
 81 def heap_sort(data):
 82     n = len(data)
 83     for i in range(n // 2 - 1, -1, -1):
 84         sift(data, i, n - 1)
 85     #堆建好了
 86     for i in range(n-1, -1, -1):            #i指向堆的最后
 87         data[0], data[i] = data[i], data[0] #领导退休,刁民上位
 88         sift(data, 0, i - 1)                #调整出新领导
 89 # def heap_sort(data):
 90 #     n = len(data)
 91 #     for i in range(n // 2 - 1, -1, -1):
 92 #         sift(data, i, n - 1)
 93 #     #堆建好了
 94 #     li = []
 95 #     for i in range(n-1, -1, -1):            #i指向堆的最后
 96 #         li.append(data[0])
 97 #         data[i] = data[0]
 98 #         sift(data,0,i-1)
 99 def merge(li, low, mid, high):
100     i = low
101     j = mid + 1
102     ltmp = []
103     while i <= mid and j <= high:
104         if li[i] < li[j]:
105             ltmp.append(li[i])
106             i += 1
107         else:
108             ltmp.append(li[j])
109             j += 1
110     while i <= mid:
111         ltmp.append(li[i])
112         i += 1
113     while j <= high:
114         ltmp.append(li[j])
115         j += 1
116     li[low:high+1] = ltmp
117 def _mergesort(li, low, high):
118     if low < high:
119         mid = (low + high) // 2
120         _mergesort(li,low, mid)
121         _mergesort(li, mid+1, high)
122         merge(li, low, mid, high)
123 @cal_time
124 def mergesort(li):
125     _mergesort(li, 0, len(li) - 1)
126 @cal_time
127 def insert_sort(li):
128     for i in range(1, len(li)):
129         tmp = li[i]
130         j = i - 1
131         while j >= 0 and li[j] > tmp:
132             li[j+1]=li[j]
133             j = j - 1
134         li[j + 1] = tmp
135 @cal_time
136 def shell_sort(li):
137     gap = int(len(li) // 2)
138     while gap >= 1:
139         for i in range(gap, len(li)):
140             tmp = li[i]
141             j = i - gap
142             while j >= 0 and tmp < li[j]:
143                 li[j + gap] = li[j]
144                 j -= gap
145             li[i - gap] = tmp
146         gap = gap // 2
147 @cal_time
148 def count_sort(li, max_num):
149     count = [0 for i in range(max_num + 1)]
150     for num in li:
151         count[num] += 1
152     i = 0
153     for num,m in enumerate(count):
154         for j in range(m):
155             li[i] = num
156             i += 1
157 @cal_time
158 def insert_sort(li):
159     for i in range(1, len(li)):
160         tmp = li[i]
161         j = i - 1
162         while j >= 0 and li[j] > tmp:
163             li[j+1]=li[j]
164             j = j - 1
165         li[j + 1] = tmp
166 # def topk(li, k):
167 #     ltmp = li[0:k + 1]
168 #     insert_sort(ltmp)
169 #     for i in range(k, len(li)):
170 #         ltmp[k]=li[i]
171 #         tmp = ltmp[k]
172 #         j = k - 1
173 #         while j >= 0 and ltmp[j] > tmp:
174 #             li[j + 1] = ltmp[j]
175 #             j = j - 1
176 #         li  [j + 1] = ltmp
177 #     return ltmp
178 def topn(li, n):
179     heap = li[0:n]
180     for i in range(n // 2 - 1, -1, -1):
181         sift(heap, i, n - 1)
182     #遍历
183     for i in range(n, len(li)):
184         if li[i] > heap[0]:
185             heap[0] = li[i]
186             sift(heap, 0, n - 1)
187     for i in range(n - 1, -1, -1):  # i指向堆的最后
188         heap[0], heap[i] = heap[i], heap[0]  # 领导退休,刁民上位
189         sift(heap, 0, i - 1)  # 调整出新领导
190     return heap
191 # sys.setrecursionlimit(100000)
192 # #data = list(range(100000, 0, -1))
193 # data = []
194 # for i in range(100000):
195 #     data.append(random.randint(0,100))
196 # # data.sort()
197 # #random.shuffle(data)
198 # data1 = copy.deepcopy(data)
199 # data2 = copy.deepcopy(data)
200 # data3 = copy.deepcopy(data)
201 # #
202 # # bubble_sort(data1)
203 # #quick_sort(data2)
204 # count_sort(data1, 100)
205 # # sys_sort(data3)
206 # #mergesort(data3)
207 # sys_sort(data3)
208 # li=[1,4,5,6,2,3,7,8,9]
209 # merge(li, 0, 3, 8)
210 # print(li)
211 li = list(range(10000))
212 random.shuffle(li)
213 print(topn(li, 10))
View Code
stack
 1 def cheak_kuohao(s):
 2     stack = []
 3     for char in s:
 4         if char in {'(','[', '{'}:
 5             stack.append(char)
 6         elif char == ')':
 7             if len(stack)>0 and stack[-1]=='(':
 8                 stack.pop()
 9             else:
10                 return False
11         elif char == ']':
12             if len(stack) > 0 and stack[-1] == '[':
13                 stack.pop()
14             else:
15                 return False
16         elif char == '}':
17             if len(stack)>0 and stack[-1]=='{':
18                 stack.pop()
19             else:
20                 return False
21     if len(stack) == 0:
22         return True
23     else:
24         return False
25 print(cheak_kuohao('()[]{{[]}}'))
View Code
test
 1 def bin_search(data_set, val):
 2     low = 0
 3     high = len(data_set) - 1
 4     while low <= high:
 5         mid = (low+high)//2
 6         if data_set[mid] == val:
 7             left = mid
 8             right = mid
 9             while left >= 0 and data_set[left] == val:
10                 left -= 1
11             while right < len(data_set) and data_set[right] == val:
12                 right += 1
13             return (left + 1, right - 1)
14         elif data_set[mid] < val:
15             low = mid + 1
16         else:
17             high = mid - 1
18     return (-1, -1)
19 def bin_search(data_set, val):
20     low = 0
21     high = len(data_set) - 1
22     while low <= high:
23         mid = (low+high)//2
24         if data_set[mid] == val:
25             left = mid
26             right = mid
27             while left >= 0 and data_set[left] == val:
28                 left -= 1
29             while right < len(data_set) and data_set[right] == val:
30                 right += 1
31             return (left + 1, right - 1)
32         elif data_set[mid] < val:
33             low = mid + 1
34         else:
35             high = mid - 1
36     return
37 li = [1,2,3,3,3,4,4,5]
38 print(bin_search(li, 5))
View Code
test2
 1 import copy
 2 li = [1, 5, 4, 2]
 3 target = 3
 4 max_num = 100
 5 def func1():
 6     for i in range(len(li)):
 7         for j in range(i+1, len(li)):
 8             if li[i] + li[j] == target:
 9                 return (i,j)
10 def bin_search(data_set, val, low, high):
11     while low <= high:
12         mid = (low+high)//2
13         if data_set[mid] == val:
14             return mid
15         elif data_set[mid] < val:
16             low = mid + 1
17         else:
18             high = mid - 1
19     return
20 def func2():
21     li2 = copy.deepcopy(li)
22     li2.sort()
23     for i in range(len(li2)):
24         a = i
25         b = bin_search(li2, target - li2[a], i+1, len(li2)-1)
26         if b:
27             return (li.index(li2[a]),li.index(li2[b]))
28 def func3():
29     a = [None for i in range(max_num+1)]
30     for i in range(len(li)):
31         a[li[i]] = i
32         if a[target-li[i]] != None:
33             return (a[li[i]], a[target-li[i]])
34 print(func3())
35 data_dict = {}
36 for i in range(len(data_list)):
37     if data_list[i] in data_dict:
38         print(data_dict[data_list[i]], i)
39     else:
40         data_dict[13 - data_list[i]] = i
View Code
topk
 1 import random
 2 def insert(li, i):
 3     tmp = li[i]
 4     j = i - 1
 5     while j >= 0 and li[j] > tmp:
 6         li[j + 1] = li[j]
 7         j = j - 1
 8     li[j + 1] = tmp
 9 def insert_sort(li):
10     for i in range(1, len(li)):
11         insert(li, i)
12 def topk(li, k):
13     top = li[0:k + 1]
14     insert_sort(top)
15     for i in range(k+1, len(li)):
16         top[k] = li[i]
17         insert(top, k)
18     return top[:-1]
19 def sift(data, low, high):
20     i = low
21     j = 2 * i + 1
22     tmp = data[i]
23     while j <= high:    #孩子在堆里
24         if j + 1 <= high and data[j] < data[j+1]:   #如果有右孩子且比左孩子大
25             j += 1  #j指向右孩子
26         if data[j] > tmp:   #孩子比最高领导大
27             data[i] = data[j]   #孩子填到父亲的空位上
28             i = j               #孩子成为新父亲
29             j = 2 * i +1        #新孩子
30         else:
31             break
32     data[i] = tmp           #最高领导放到父亲位置
33 def topn(li, n):
34     heap = li[0:n]
35     for i in range(n // 2 - 1, -1, -1):
36         sift(heap, i, n - 1)
37     #遍历
38     for i in range(n, len(li)):
39         if li[i] < heap[0]:
40             heap[0] = li[i]
41             sift(heap, 0, n - 1)
42     for i in range(n - 1, -1, -1):  # i指向堆的最后
43         heap[0], heap[i] = heap[i], heap[0]  # 领导退休,刁民上位
44         sift(heap, 0, i - 1)  # 调整出新领导
45     return heap
46 data = list(range(10000))
47 random.shuffle(data)
48 print(topn(data, 10))
View Code

 PPT

posted on 2018-01-24 19:41  我很好u 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/jyh-py-blog/p/8343238.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值