<图解算法>读后笔记

1. 二分查找
def binary_search(li, num):
    """
    :param li: 有序列表 
    :param num: 指定数字
    :return: 
    """
    low = 0
    high = len(li) - 1
    while low <= high:
        mid = int((low+high) / 2)
        guess = li[mid]
        if guess == num:
            return mid
        elif guess > num:
            high = mid - 1
        else:
            low = mid + 1
    return None
2. 选择排序
li = [1, 5, 7, 3, 2, 9]

def selection_sort(li):
    result = []
    for i in range(len(li)):
        minest = min(li)
        result.append(li.pop(li.index(minest)))
    return result
3. 快速排序
li = [1, 5, 7, 3, 2, 9]

def quicksort(li):
    if len(li) <= 1:
        return li
    guard = li[0]
    less = [l for l in li[1:] if l < guard]
    more = [l for l in li[1:] if l >= guard]
    return quicksort(more) + [guard] + quicksort(less)
4. fibonacci
def fibonacci(num):
    if num <= 0:
        return None
    elif num <= 2:
        return 1
    return fibonacci(num-1) + fibonacci(num-2)

def fib2(num):
    a, b = 0, 1
    for i in range(num):
        a, b = b, a + b
    return a
5. 广度优先算法

查找最短路径, 无向图


广度优先算法.png
graph = {
    'alice': ['peggy'],
    'anuj': [],
    'bob': ['anuj', 'peggy'],
    'claire': ['thom', 'jonny'],
    'jonny': [],
    'peggy': [],
    'thom': [],
    'you': ['alice', 'bob', 'claire']
}
from collections import deque

def search(name):
    search_queue = deque()
    search_queue += graph[name]
    searched = []

    while search_queue:
        person = search_queue.popleft()
        if person in searched:
            continue
        if check_person(person):
            print(f"{person} is the man")
            return True
        else:
            searched.append(person)
            search_queue += graph[person]
    return False
6. 狄克斯特拉算法

加权图, 查找最短路径
无负权边


狄克斯特拉算法.png
infinity = float("inf")
graph = {
    'a': {'b': 4, 'd': 2},
    'b': {'d': 6, 'fin': 3},
    'c': {'a': 8, 'd': 7},
    'd': {'fin': 1},
    'fin': {},
    'start': {'a': 5, 'c': 2}
}
costs = {
    "a": 5,
    "c": 2,
    "b": infinity,
    "d": infinity,
    "fin": infinity
}
parents = {
    "a": "start",
    "c": "start"
}
selected = []

def find_lowest_cost_node(costs):
    lowest_node = None
    lowest_cost = infinity
    for node, cost in costs.items():
        if node in selected:
            continue
        if cost < lowest_cost:
            lowest_cost = cost
            lowest_node = node
    return lowest_node

def shortest_path():
    node = find_lowest_cost_node(costs)
    while node:
        cost = costs[node]
        neighbours = graph[node]
        for n in neighbours:
            new_cost = cost + neighbours[n]
            if new_cost < costs[n]:
                costs[n] = new_cost
                parents[n] = node
        selected.append(node)
        node = find_lowest_cost_node(costs)
    return costs
7. 贪婪算法

选出覆盖所有州的电台


贪婪算法.png
stations = {
    'kfive': {'az', 'ca'},
    'kfour': {'nv', 'ut'},
    'kone': {'id', 'nv', 'ut'},
    'kthree': {'ca', 'nv', 'or'},
    'ktwo': {'id', 'mt', 'wa'}
}

def select_stations():
    states_need = {'az', 'ca', 'id', 'mt', 'nv', 'or', 'ut', 'wa'}
    stations_selected = []
    while states_need:
        best_station = None
        states_covered = set()
        for k, v in stations.items():
            covered = states_need.intersection(v)
            if len(covered) > len(states_covered):
                states_covered = covered
                best_station = k
        stations_selected.append(best_station)
        states_need -= states_covered
    return stations_selected
8. 最长公共子串
最长公共子串.png
9. 最长公共子序列
最长公共子序列.png
if word_a[i] == word_b[j]:
    cell[i][j] = cell[i-1][j-1] + 1
else:
    cell[i][j] = max(cell[i][j-1], cell[i-1][j])
番外: 嫌疑人问题

a: 凶手不是我
b: 凶手是c
c: 凶手是d
d: c在说谎
四个人里有一个人在说谎, 问凶手是谁

for l in ["a", "b", "c", "d"]:
    if ((l != 'a') + (l == 'c') + (l == 'd') + (l != 'd')) == 3:
        print(l)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356