1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance

題目
思路:

  • 要找的點是可到達的點的距離在 threshold 裡的那些點,所以要找的是最短距離,因為只要最短距離可以在 threshold 內,那它就是可到達的點
  • 用 Floyd-Warshall’s algorithm 找到所有點之間的最小距離
    • kij 之間的任意點。比較 i -> j 經過所有 k 的距離,最小的即為 i -> j 的最短距離。
    • Question:
      if the path is i -> 2 -> 1 -> j and the iteration consider k == 1 first. But the dist[i][1] not yet populated and still have value of float('inf'). It will have the actual value until k == 2.

[Python] list 用 `.extend()` 與 `+=` 的差別

譬如有兩個 list ab,使用 a.extend(b)a += b 有什麼相同或不同?有沒有什麼 general 的 best practice for using one rather than the other?

其實在這個情境下,這兩個用法幾乎一樣。它們都會直接 in-place 的修改 a,把 b 裡面的元素加到 a 的後面

  • += 會呼叫 list 的 .__iadd__() 來做 in-place 的修改
    • 所以在這個情境下,b 可以是任何 iterable,譬如 [] += {} 會得到 []
    • 假如用 += 的是 immutable 的 type,Python 發現沒有 .__iadd__(),接著就會呼叫它的 .__add__(),此情況下 a += b 等同於 a = a + b

以下列出少數有差別的地方:

409. Longest Palindrome

題目
思路

  1. 怎麼判斷一個 string 是否為 palindrome?
    • (x) 做一個倒過來的 string 看看兩個是否相等
      • 需要 O(n) 時間複雜度,太長了,因為你必須對所有的字串組合做測試
    • (o) Palindrome 一定是由偶數個數的字母組成,頂多再加上一組奇數個數的字母
  2. 先用 dict 記錄每個 character 的個數,再利用計算完成的 dict 來算出答案

為什麼 Python 的 in 用在 set 是 O(1) 時間複雜度?

通常都會說 Python 的 set 內部是用 hash table 來實作,所以是 O(1),但為什麼這樣就是 O(1)?

當要判斷某個元素是否在 set 裡面時,它的 __hash__() 會被用來得到 hash 值,可以把這個 hash 值視為 set 底層實作的 array 的 index,Python 接著會用這個 hash 值去那個 array 的對應位置找,然後發現 array 沒有這個位置,或是找到對應 value,而這個過程跟 set 裡的元素個數無關,所以是 O(1)

而這邊說的 O(1) 是平均時間複雜度,最壞情況時間複雜度是 O(n),

142. Linked List Cycle II

題目
思路:最直覺的作法就是從頭開始沿著 next 一直走,然後用一個 set 來存放走過的 node,如果再次走到已走過的 node 就是 cycle 起點

為什麼 Python dict 的 get item operation 時間複雜度為 O(1) ?

如果去 google,大部分查到的都會說因為 Python 會把 key 經過 hash function 運算,得到一個 dict 真正內部在使用的 key,從而找到對應的 value。而一個好的 hash function 它的運算所需時間是不會隨著 n 增加而變大的,所以 dict 的 get item operation 時間複雜度為 O(1) 。

不過我的疑惑是,經過 hash function 運算得到 key 之後,由這個 key 去找到 value 的時間複雜度是 O(1) 嗎?除非這個也是 O(1) 才能說整個 get item operation 是 O(1) 。

用 pipenv 管理 requirements 搭配 docker-compose local 開發

  • Local 開發是跑在 Docker 的虛擬環境裡,所以 Pipenv 產生的虛擬環境只是用來裝套件產生 Pipfile.lock 而已
  • 用 pipenv 就不用自己寫 requirements.txt,不但可以自動安裝最新版的套件,而且可以很輕鬆的固定住對應 sub-packages 的版本
  • 想一次更新所有套件也很容易
  • 步驟:(以裝一個 package 為例)

Effective Python Note 2

This article is composed of some notes from book Effective Python.

Use @property to define special behavior when attributes are accessed/set on your objects, if necessary

Another use case is to only specify getter to make that attribute read-only.

Effective Python Note

This article is composed of some notes from book Effective Python.

Scope Resolution

Python’s scope resolution follows the order below:

  1. current function
  2. enclosing scopes: like a outer function enclosing the current function
  3. global scope
  4. build-in scope
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×