算法图解的代码实现
发布于:2019-12-08 23:05:22
访问:
最近在看《算法图解》,书写的很棒,于是我决定把上面提到的算法依次实现一下,代码放在文章中做留存。 第一章:二分查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import randomlow = 0 hight = 100 numberlist = list (range (0 , 100 )) guess_number = random.randint(0 ,100 ) print (guess_number)while True : mid = round ((low+ hight) / 2 ) if guess_number == numberlist[mid]: print ('Guess number is ' ,guess_number) break elif guess_number > numberlist[mid]: low = mid elif guess_number < numberlist[mid]: hight = mid else : print ('Has someting woring.' )
第二章:选择排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 def findSmallest (arr ): smallest = arr[0 ] smallest_index = 0 for i in range (1 , len (arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selectionSort (arr ): newArr = [] for i in range (len (arr)): smallest = findSmallest(arr) newArr.append(arr.pop(smallest)) return newArr arr = [5 ,3 ,6 ,10 ,2 ] print (selectionSort(arr))
第四章:快速排序
1 2 3 4 5 6 7 8 9 10 11 def quicksort (array ): if len (array) < 2 : return array else : pivot = array[0 ] less = [i for i in array[1 :] if i <= pivot] greater = [i for i in array[1 :] if i > pivot] return quicksort(less) + [pivot] + quicksort(greater) print (quicksort([1 ,5 ,8 ,9 ,3 ,4 ,7 ,10 ]))
第六章:广度优先收索
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 from collections import dequedef person_is_seller (name ): return name[-1 ] == "m" def search (name ): search_queue = deque() search_queue += graph[name] searched = [] while search_queue: person = search_queue.popleft() if not person in searched: if person_is_seller(person): print (person + " is a mongo seller!" ) return True else : search_queue += graph[person] searched.append(person) return False search("you" )
第七章:狄克斯特拉算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 import mathgraph = {} graph["start" ] = {} graph["start" ]["a" ] = 6 graph["start" ]["b" ] = 2 graph["a" ] = {} graph["a" ]["fin" ] = 1 graph["b" ] = {} graph["b" ]["a" ] = 3 graph["b" ]["fin" ] = 5 graph["fin" ] = {} print (graph)costs = {} costs["a" ] = 6 costs["b" ] = 2 costs["fin" ] = math.inf print (math.inf,type (math.inf))parents = {} parents["a" ] = "start" parents["b" ] = "start" parents["fin" ] = None processed = [] def find_lower_cost_node (costs ): lowest_cost = math.inf lowest_cost_node = None for node in costs: cost = costs[node] if cost < lowest_cost and node not in processed: lowest_cost = cost lowest_cost_node = node return lowest_cost_node node = find_lower_cost_node(costs) while node is not None : cost = costs[node] neighbors = graph[node] for n in neighbors.keys(): new_cost = cost + neighbors[n] if costs[n] > new_cost: costs[n] = new_cost parents[n] = node processed.append(node) node = find_lower_cost_node(costs) print (costs)