《算法图解》笔记

坚强是说给别人听的谎言 提交于 2021-02-10 10:02:38
 
算法的运行时间并不以秒为单位。
 算法的运行时间是其从增速的角度衡量的。
 算法的运行时间用大O表示法表示

 

1.二分查找输入是一个有序列表。

  

def binary_search(list1, item):
  """
  二分查找的速度比简单查找快很多。
  O(log n)比O(n)快。需要搜索的元素越多,前者就比后者快得越多。
  """
  start = 0
  end = len(list1) - 1

  while start <= end:
    middle = int((start+ end) / 2)
    guess = list1[middle]
    if guess == item:
      return middle
    elif guess > item:
      end = middle - 1
    else:
      start = middle+1
  return None
 
2.选择排序
  
def findSmallest(arr):
  smallest = arr[0]
  small_index = 0
  for i in range(1, len(arr)):
    if arr[i] < smallest:
    smallest = arr[i]
    small_index = i
  return small_index

def selectionSort(arr):
  out = []
  while arr:
  out.append(arr.pop(findSmallest(arr)))
  return out
 
3.快速排序
 
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)
 
4.广度优先搜索
 
def search():
  graph = {}
  graph["you"] = ["alice", "bob", "claire"]
 
  graph["bob"] = ["anuj", "peggy"]
  graph["alice"] = ["peggy"]
  graph["claire"] = ["thom", "jonny"]

  graph["anuj"] = []
  graph["peggy"] = []
  graph["thom"] = []
  graph["jonny"] = []

  from collections import deque
  search_queue = deque()
  search_queue += graph["you"]

  def person_is_seller(name):
    return name[-1] == 'm'

  while search_queue:
    person = search_queue.popleft()
    if person_is_seller(person):
      print(person+"is a mango seller")
      return True
    else:
      search_queue += graph[person]
    return False
 
5.狄克斯特拉算法
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2

graph["a"] = {}
graph["a"]["end"] = 1

graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["end"] = 5

graph["end"] = {}

infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["end"] = infinity

parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["end"] = None

processed= []

def find_lowest_cost_node(costs):
  lowest_cost = float("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_lowest_cost_node(costs)

while node is not None:
  nb = graph[node]
  for n in nb.keys():
    new = costs[node]+nb[n]
    if costs[n] > new:
      costs[n] = new
      parents[n] = node
  processed.append(node)
  node = find_lowest_cost_node(costs)
 
5.贪婪算法
states_needed = set(["mt", "wa", "or", "id", "nv", "ut", "ca", "az"]) # 要覆盖的州

stations = {} # 可选择的广播台清单
stations["kone"] = set(["id", "nv", "ut"])
stations["ktwo"] = set(["wa", "id", "mt"])
stations["kthree"] = set(["or", "nv", "ca"])
stations["kfour"] = set(["nv", "ut"])
stations["kfive"] = set(["ca", "az"])

final_stations = set()   # 存储最终选择的广播台

while states_needed:

    best_station = None     # 覆盖了最多的未覆盖州的广播台
    states_covered = set()    # 该广播台覆盖的所有未覆盖的州

    for station, states_for_station in stations.items():
        covered = states_needed & states_for_station
        if len(covered) > len(states_covered):
            best_station = station
            states_covered = covered

    final_stations.add(best_station)
    states_needed -= states_covered
print(final_stations)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!