zoukankan      html  css  js  c++  java
  • 算法图解读书笔记:附程序

    算法图解通俗易懂,下面是随书练习程序,基于python3

    二分法

    #二分法
    def binary_search(list, item):
        low = 0
        high = len(list)-1
        while low <= high:
            mid = (low + high)
            guess = list[mid]
            if guess == item:
                return mid
            if guess > item:
                high = mid - 1
            else:
                low = mid + 1
        return None
    my_list = [1, 3, 5, 7, 9]
    print(binary_search(my_list, 3)) #  1
    print(binary_search(my_list, -1)) #  None

    排序

    #排序
    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]))

    递归

    #递归方式实现倒计时
    def countdown(i):
        print(i)
        if i <= 0:
            return
        else:
            countdown(i-1)
    print(countdown(5))

    #调用栈
    def greet2(name):
        print("how are you, " + name + "?")
    def bye():
        print("ok bye!")
    def greet(name):
        print("hello, " + name + "!")
        greet2(name)
        print("getting ready to say bye...")
        bye()
    print(greet('jiaweican'))

    递归调用栈

    #递归调用栈
    def fact(x):
        if x == 1:
            return 1
        else:
            return x * fact(x-1)
    print(fact(5))

    求和

    def sum(arr):
        total = 0
        for x in arr:
            total += x
        return total
    print(sum([1, 2, 3, 4]))

    递归方法求和

    #递归方法实现求和
    def sum(arr):
        n=len(arr)
        if n>0:
            a=arr[0]
            arr.remove(arr[0])
            return sum(arr)+a
        else:
            return 0
    print(sum([1,3,5]))

    递归方法计数

    #递归方法实现计算列表元素个数
    def count(arr):
        a=1
        if arr==[]:
            return 0
        else:
            arr.remove(arr[0])
            return count(arr)+a
    print(count([1,1,1,2,1,1,1]))

    快速排序

    #快速排序
    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([10, 5, 2, 3]))

    搜索

    voted = {}
    def check_voter(name):
        if voted.get(name):
            print("kick them out!")
        else:
            voted[name] = True
            print("let them vote!")
    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
    def 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 mango seller!")
                    return True
                else:
                    search_queue += graph[person]
                    searched.append(person)
        return False
    search("you")

    贪婪算法

    #贪婪算法
    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 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)
  • 相关阅读:
    如何设置ASP.NET页面的运行超时时间
    日志文件清理工具V1.1
    【原创】日志文件清理工具V1.0
    【分享】国外后台界面HTML源码 [免费]
    【分享】仿东软OA协同办公服务管理源码
    年底发福利了——分享一下我的.NET软件开发资源
    由12306动态验证码想到的ASP.NET实现动态GIF验证码(附源码)
    【分享】元旦送礼,商业源码免费赠送!
    给大家分享一个jQuery TAB插件演示
    【分享】双12了,也没啥可送大家的,就送大家点商业源码吧!
  • 原文地址:https://www.cnblogs.com/xiyouzhi/p/9603135.html
Copyright © 2011-2022 走看看