算法图解读书笔记:附程序

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

 

posted @ 2018-09-07 17:06  西柚汁  阅读(375)  评论(0)    收藏  举报