博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
算法图解读书笔记:附程序
阅读量:5164 次
发布时间:2019-06-13

本文共 3720 字,大约阅读时间需要 12 分钟。

算法图解通俗易懂,下面是随书练习程序,基于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)) #  1print(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)

 

转载于:https://www.cnblogs.com/xiyouzhi/p/9603135.html

你可能感兴趣的文章
不同程序语言的注释和变量要求
查看>>
语言基础(9):static, extern 和 inline
查看>>
ES5_03_Object扩展
查看>>
bzoj 2600: [Ioi2011]ricehub
查看>>
创建数据库,表
查看>>
工厂模式
查看>>
计算机网络基础知识
查看>>
C#里如何遍历枚举所有的项
查看>>
如何在键盘出现时滚动表格,以适应输入框的显示
查看>>
超级强大的鼠标手势工具
查看>>
常用Dockerfile举例
查看>>
jquery的ajax用法
查看>>
设计模式-策略模式(Strategy)
查看>>
django orm 数据查询详解
查看>>
JarvisOJ Basic 熟悉的声音
查看>>
C# list导出Excel(二)
查看>>
CAS 单点登录模块学习
查看>>
跟着辛星用PHP的反射机制来实现插件
查看>>
Android应用开发-网络编程①
查看>>
input中的name,value以及label中的for
查看>>