算法圖解:Python筆記代碼

二分查找node

選擇排序算法

遞歸數據結構

快速排序app

廣度優先搜索less

狄克斯特拉算法ui

貪婪算法spa

二分查找

def binary_search(lst,item):
    low = 0
    high = len(lst)-1
    
    while low <= high:
        mid = (high+low)//2
        if item == lst[mid]:
            return mid
        if item < lst[mid]:
            high = mid-1
        if item > lst[mid]:
            low = mid + 1
    return None


my_list = [1,3,5,7,9]
print(binary_search(my_list,5))

選擇排序

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 selection_Sort(arr):
    new_arr = []
    for i in range(len(arr)):
        new_arr.append(arr.pop(findsmallest(arr)))  # 注意pop的對象是索引
    return new_arr


arr = [3,1,5,2,9,1,1,0]
print(selection_Sort(arr))

遞歸

# 倒計時
def countdown(n):
    print(n)
    if n < 1:
        return
    countdown(n-1)


# 求和
def sum_1(arr):
    if arr == []:
        return 0
    return arr.pop(0) + sum_1(arr)

def sum_2(arr):
    if arr == []:
        return 0
    return arr[0] + sum_2(arr[1:])


arr = [1,2,3,4,5]
print(sum_1(arr))

# 階乘
def fact(n):
    if n == 1:
        return 1
    return n * fact(n - 1)

# 計算元素個數
def count_arr(arr):
    if arr == []:
        return 0
    return 1 + count_arr(arr[1:])

快速排序

def quick_sort(arr):
    if len(arr) < 2:
        return arr
    else:
        pivot = arr[0]
        less = [i for i in arr[1:] if i <= pivot]
        greater = [i for i in arr[1:] if i > pivot]
        return quick_sort(less) + pivot + quick_sort(greater)

廣度優先搜索

# 使用隊列這種數據結構
from collections import deque 

# 定義圖
graph = {
    'you': ['alice', 'bob', 'claire'], 
    'bob': ['anuj', 'peggy'], 
    'alice': ['peggy'], 
    'claire': ['thom', 'jonny'], 
    'anuj': [], 
    'peggy': [], 
    'thom': [],
    'jonny': []
    }

# 判斷是不是芒果銷售商   
def person_is_seller(name):
    return name[-1] == "m"

# 廣度優先搜索
def search(name):
    # 實例化隊列
    search_deque = deque()
    # 將某人的一度關係網加入到隊列中
    search_deque += graph[name]
    # 初始化已檢查過的人
    searched = []

    # 隊列中存在元素時就一直搜索
    while search_deque:
        # 從列隊中彈出第一我的,並檢查
        person = search_deque.popleft()
        # 此人不在已檢查過的列表中
        if person not in searched:
            # 檢查是不是銷售商
            if person_is_seller(person):
                print("%s is mango_seller" % person)
                return True
            else:
                # 若是不是就將此人的一度關係網加入到隊列中
                search_deque += graph[person]
                searched.append(person)

    return False


search("you")

狄克斯特拉算法

# 建立圖的散列表
graph = {
    "start":{"a":6,"b":2},
    "a":{"fin":1},
    "b":{"a":3,"fin":5},
    "fin":{}
}
# 建立開銷的散列表
costs = {
    "a":6,
    "b":2,
    "fin":float("inf")
}
# 建立存儲父節點的散列表
parents = {
    "a":"start",
    "b":"start",
    "fin": 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:
    cost = costs[node]
    neighbors = graph[node]
    # 三、遍歷鄰居
    for n in neighbors.keys():
        # 計算該節點到鄰居的開銷+起點到該節點的開銷,與起點直接到改點的開銷比較
        new_cost = cost + neighbors[n]
        # 若是前者開銷較小則更新改鄰居節點的父節點,並更新起點到該鄰居節點的開銷
        if new_cost < costs[n]:
            parents[n] = node
            costs[n] = new_cost
    # 四、將當前節點標記爲處理過
    processed.append(node)
    # 五、找出接下來要處理的節點並循環
    node = find_lowest_cost_node(costs)

print(processed)
print(costs)
print(parents)

貪婪算法

# 目標:選擇儘量少的電臺覆蓋儘量多的州
# 方法:第一步,選擇覆蓋州最多的電臺
# 方法:第二步,選擇覆蓋最多「未覆蓋的州(上一步剩下的州)」的電臺
# 方法:第三步,重複第二步,直到覆蓋全部的州

# 須要覆蓋的州
states_needed = set(["mt", "wa", "or", "id", "nv", "ut","ca", "az"])

# 電臺清單
stations = {
    "kone" : set(["id", "nv", "ut"]),
    "ktwo" : set(["wa", "id", "mt"]),
    "kthree" : set(["or", "nv", "ca"]),
    "kfour" : set(["nv", "ut"]),
    "kfive" : set(["ca", "az"])
}

# 該集合存儲最終選擇的電臺
final_stations = set()

# 只要須要覆蓋的州不爲空就一直循環
while states_needed:
    best_station = None
    states_covered = set()
    # 從電臺清單中找出覆蓋未覆蓋州最多的電臺
    for station,states in stations.items():
        covered = states_needed & states
        if len(covered) > len(states_covered):
            best_station = station
            states_covered = covered

    # 每次肯定一個最佳的電臺就將其覆蓋的州從總集合中減去
    states_needed -= states_covered
    # 沒肯定一個最佳電臺就存在最終的電臺集合中
    final_stations.add(best_station)

print(final_stations)
相關文章
相關標籤/搜索