算法图解代码区

排序算法

#排序算法,找出最小值,移除数组内内的最小值,然后append连接
#寻找数组中的最小数
from numba.cgutils import printf
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

print(selectionSort([5,3,6,2,10]))

二分法

#二分法查找
my_list=[1,3,5,7,9]

def binary_search(list,item):
    low=0;            #low和hign设定查找的范围,如果查找的值不在范围内,返回为none
    high=len(list)-1

    while low <=high:  #只要上下的范围没有同意就继续查找
        mid = int(low + (high - low) / 2 ) #修改mid=(low+high)/2 防止范围过大导致的相加溢出问题
                                           #添加int进行强转,因为列表索引必须是整型或切片
        guess =list [mid]
        if guess == item :
            return mid
        if guess > item :
            high = mid - 1
        if guess < item :
            low = mid + 1
    return None

print(binary_search(my_list,3))
print(binary_search(my_list,-1))

数组累积和

#循环实现数组累加和
 def sum(arr):
     total =0
     for x in arr :
         total = x + total
     return total

 print(sum([1,2,3,4]))

快速排序:

#快速排序
#单个的数组直接排序
def quicksort(array):
    if len(array)<2:
        return array   #为空或者只包含一个元素的数组是有序的
    else:
        pivot =array[0]
        # 快速循环判断,将结果形成新的列表
        # 从列表array的第1个元素开始判断是否小于pivot,如果是则放到一个新的列表中。
        less =[i for i in array[1:] if i <= pivot]
        # 从列表array的第1个元素开始判断是否大于pivot,如果是则放到一个新的列表中。
        greater =[i for i in array[1:] if i > pivot]
        return quicksort(less)+[pivot]+quicksort(greater)   #[]python的列表支持printf和+运算
        # arry = [1, 5, 7] + [6, 8, 2]
        # print(arry)
print(quicksort([10,5,2,3,8,10,7]))

广度优先算法:

#广度优先算法
#解决问题:1.路径是否存在? 2.路径最短问题
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"]=[]

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

from collections import deque
def search(name):
    search_queue=deque()
    search_queue +=graph[name]
    searched=[]
    while search_queue:
        person=search_queue.popleft()  #popleft为出队,先进先出,为队列特有方式
        if person not in searched:
            if person_is_seller(person):
                print(person+" is a mango seller")
                return True
            else:
                search_queue += graph[person]
                searched.append(person)
    return False

search("you")

狄克斯特拉算法

#狄克斯特拉算法
# 构造全图字典graph
graph = {}
graph["start"] = {} # 使用字典中的字典
graph["start"]["a"] = 6
graph["start"]["b"] = 2
#print (graph["start"].keys())  #查看节点的邻居
#print (graph["start"]["a"])   #查看节点的值
graph["a"]={}
graph["a"]["fin"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5
graph["fin"] = {}
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["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

def main(graph,costs,parents,processed,infinity):
    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 costs[n] > new_cost:
                costs[n] = new_cost
                parents[n] = node
        processed.append (node)
        node = find_lowest_cost_node (costs)

main(graph,costs,parents,processed,infinity)
print(costs)
print(parents)

猜你喜欢

转载自blog.csdn.net/GongmissYan/article/details/114316385