<圖解算法>讀后筆記

1. 二分查找
def binary_search(li, num):
    """
    :param li: 有序列表 
    :param num: 指定數(shù)字
    :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. 廣度優(yōu)先算法

查找最短路徑, 無向圖


廣度優(yōu)先算法.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)
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末止吁,一起剝皮案震驚了整個濱河市廷没,隨后出現(xiàn)的幾起案子怀跛,更是在濱河造成了極大的恐慌胧辽,老刑警劉巖儡循,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件码泛,死亡現(xiàn)場離奇詭異收津,居然都是意外死亡,警方通過查閱死者的電腦和手機菩颖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門样漆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人晦闰,你說我怎么就攤上這事放祟。” “怎么了呻右?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵跪妥,是天一觀的道長。 經(jīng)常有香客問我窿冯,道長骗奖,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任醒串,我火速辦了婚禮执桌,結果婚禮上,老公的妹妹穿的比我還像新娘芜赌。我一直安慰自己仰挣,他們只是感情好,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布缠沈。 她就那樣靜靜地躺著膘壶,像睡著了一般。 火紅的嫁衣襯著肌膚如雪洲愤。 梳的紋絲不亂的頭發(fā)上颓芭,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機與錄音柬赐,去河邊找鬼亡问。 笑死,一個胖子當著我的面吹牛肛宋,可吹牛的內(nèi)容都是我干的州藕。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼酝陈,長吁一口氣:“原來是場噩夢啊……” “哼床玻!你這毒婦竟也來了?” 一聲冷哼從身側響起沉帮,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤锈死,失蹤者是張志新(化名)和其女友劉穎贫堰,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體馅精,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡严嗜,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年粱檀,在試婚紗的時候發(fā)現(xiàn)自己被綠了洲敢。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡茄蚯,死狀恐怖压彭,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情渗常,我是刑警寧澤壮不,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站皱碘,受9級特大地震影響询一,放射性物質發(fā)生泄漏。R本人自食惡果不足惜癌椿,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一健蕊、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧踢俄,春花似錦缩功、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至琳钉,卻和暖如春势木,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背歌懒。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工啦桌, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人歼培。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓震蒋,卻偏偏與公主長得像,于是被迫代替她去往敵國和親躲庄。 傳聞我的和親對象是個殘疾皇子查剖,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355