算法图解之python算法

二分法

def 二分法(list,item):
    low,high=0,len(list)-1
    mid=0
    while low<=high:
        mid=int((low+high)/2)
        guess=list[mid]
        if guess==item:
            return mid
        elif guess>item:
            high=mid-1
        else:
            low=mid+1
    return None #没有指定元素时退出
mylist=[1,3,4,6,7]
item=int(input("请输入你要查找的数:"))
print("所在的位置为第",二分法(mylist,item)+1,"个数字")

选择排序

def selectionsort(arr):
    for i in range(len(arr)-1):
        z=i
        for j in range(i+1,len(arr)):
            if arr[z]>arr[j]:
                z=j
        if z!=i:
            arr[i],arr[z]=arr[z],arr[i]
    return arr
print(selectionsort([1,4,6,6,2,4,1,14,2,1,123]))

递归
demo1(内存中的调用栈)
demo2(快速排序)
练习1(用递归实现列表元素的相加)
练习2(用递归计算列表包含的元素数)
练习3(用递归找出列表中的最大值)

def look_for_key(box):
    for item in box:
        if item.is_a_box():##递归条件
            look_for_key(box)
        elif item.is_a_key():##基线条件
            print("found the key!")

    #demo1(内存中的调用栈)
    def greet2(name):
        print("how are you," + name + "?")

    def bye():
        print("ok bye")

    def greet(name):
        print("hello " + name + "!")
        greet2(name)
        print("getting read to say bye..")
        bye()

    greet("段誉")

    #demo2(快速排序)
    def quicksort(array):
        if \
                (len(array) < 2):
            return array
        else:
            mid = array[0]
            less = [i for i in array[1:] if i <= mid]
            bigger = [i for i in array[1:] if i > mid]
            return quicksort(less) + [mid] + quicksort(bigger)

    print(quicksort([2, 1, 4, 6, 3]))

    #练习1(用递归实现列表元素的相加)
    def sum(list):
     if list == []:
        return 0
     return list[0] + sum(list[1:])
    list=[1,2,3,4]
    print(sum(list))
    #练习2(用递归计算列表包含的元素数)
    def count(list):
       if list==[]:
         return 0
       return 1+count(list[1:])
    list=[1,2,3,4]
    print(count(list))
    #练习3(用递归找出列表中的最大值)
    def find_max_in_list(list):
      if len(list)==2:
           if(list[0]>list[1]):
               return list[0]
           return list[1]
      sub_max=find_max_in_list(list[1:])
      if list[0]>sub_max:
        return list[0]
      return sub_max
    list=[9,3,5,7]
    print(find_max_in_list(list))

散列表(字典)
demo1(判断是否投票)
demo2(网页缓存原理)

    #创建字典
book={}
book["apple"]=0.67
book["milk"]=1.49
book["avocado"]=1.49
print(book)
print(book["milk"])

    #demo1(判断是否投票)
voted={}
def check_voter(name):
    if voted.get(name):
        print("投了")
    else:
        voted[name]=True
        print("没投票")
check_voter("dy")
check_voter("dsa")
check_voter("dy")

    #demo2(网页缓存原理)
cache = {}
def get_page(url):
    if cache.get(url):
        return cache[url]
    else:
        data = get_data_from_serer(url)
        cache[url] = data
        return data

广度优先搜索
demo1(查找销售商)

    #demo1(查找销售商)
from collections import deque
def person_is_seller(person):
    return person=="zb"
def search(name):
    search_queue=deque()##创建队列
    search_queue+=graph[name]
    searched=[]
    while search_queue:
        person=search_queue.popleft()
        if person not in searched:
            if person_is_seller(person):
                print("就是"+person)
                return True
            else:
                search_queue+=graph[person]
                searched.append(person)
    print("没有这个人")
    return False
graph={}
graph["a1"]=["b1","b2"]
graph["b1"]=["c1","c2"]
graph["c1"]=["dy","d1"]
graph["b2"]=[]
graph["c2"]=[]
graph["d1"]=[]
graph["dy"]=[]
search("a1")

狄克斯特拉算法(加权图)(适用于有向无环图)
demo1(最短路径问题)

#demo1(最短路径问题)
from pprint import pprint
graph1={}#第一个散列表(创建节点散列表)
graph1['start']={}
graph1['start']['a']=6
graph1['start']['b']=2

graph1['a']={}
graph1['a']['end']=1

graph1['b']={}
graph1['b']['a']=3
graph1['b']['end']=5

graph1['end']={}


graph2={}#第二个散列表(存储每个节点的开销)
infinity=float('inf')#将未知的开销设置为无穷大
graph2['a']=6
graph2['b']=2
graph2['end']=infinity


parents={}#第三个散列表(存储父节点)
parents['a']='start'
parents['b']='start'
parents['end']=None

processed=[]

def find_lowest_cost_node(graph2):
    lowest_cost=infinity
    lowest_cost_node=None
    for node in graph2:
        cost=graph2[node]
        if cost<lowest_cost and node not in processed:
            lowest_cost=cost
            lowest_cost_node=node
    return lowest_cost_node

def get_lowest_cost():
    node=find_lowest_cost_node(graph2)
    while node is not None:
        cost=graph2[node]
        neighbor=graph1[node]
        for n in graph1[node].keys():
            new_cost=cost+neighbor[n]
            if graph2[n]>new_cost:
                graph2[n]=new_cost
                parents[n]=node
        processed.append(node)
        node=find_lowest_cost_node(graph2)
    return cost



def get_end_path(val):
    for node in parents:
        if parents[node] == val:
            path.append(node)
            val=node
    if val != 'end':
        get_end_path(val)
    end_path='——>'.join(path)
    return end_path

if __name__ == '__main__':
    lowest_cost = get_lowest_cost()
    print('最低开销为:' + str(lowest_cost))
    path = ['start']  # 路线初始节点
    end_path = get_end_path('start')
    print('最低开销路线为:' + end_path)
    pprint(graph1)

贪婪算法
demo1:广播覆盖问题

states_needed=set(["a","b","c","d","e","f","g","h"])
stations={}
stations["k1"]=set(["b","c","d"])
stations["k2"]=set(["c","d","e"])
stations["k3"]=set(["d","e","f"])
stations["k4"]=set(["a","b","c","d"])
stations["k5"]=set(["g","h"])

fina_stations=set()


while states_needed :
    best_station = None
    states_covered = set()
    for station,states in stations.items():
         coverd=states_needed & states##计算交集
         if len(coverd)>len(states_covered):
           best_station=station
           states_covered=coverd
    states_needed-=states_covered
    fina_stations.add(best_station)

print(fina_stations)

发布了8 篇原创文章 · 获赞 0 · 访问量 137

猜你喜欢

转载自blog.csdn.net/weixin_45314989/article/details/104333394