2019年10月15日 星期二

Python 遞迴初學

最近用 python 刷題

刷到要用 DFS 的題目,想用遞迴去寫才發現 python 沒有指標

看著討論的 python 大神寫的程式碼,發現都是 python 裡的參數都是指標

下面拿一題示範 0947 - Most Stones Removed with Same Row or Column

class Solution:
     
     def removeStones(self, stones: List[List[int]]) -> int:
          
          # 想像用 垂直線 跟 水平線 去想辦法連接所有石頭
          # 連接了 n 個, 代表可以去掉 n -1, 看圖
                 
          # 初始樹的數目 以及 複製一個 stones 去做 DFS
          treeNum = 0
          points = {(i, j) for i, j in stones}
          
          # 建立 row 跟 col 兩個 List
          # row 紀錄該 index 下的所有有石頭的 y 座標值
          # col 紀錄該 index 下的所有有石頭的 x 座標值
          row = collections.defaultdict(list)
          col = collections.defaultdict(list)
          for i, j in stones:
               row[i].append(j)
               col[j].append(i)

          for i, j in stones:
               if (i, j) in points:
                    self.dfs(i, j, row, col, points)
                    treeNum += 1

          return len(stones) - treeNum
     
     def dfs(self, x, y, row, col, points):
          
          # 刪除這個點
          points.discard((x, y))

          # 此兩個刪除是為了加速計算
          #row[x].remove(y)
          #col[y].remove(x)

          for i in row[x]:
               if (x, i) in points:
                    self.dfs(x, i, row, col, points)

          for i in col[y]:
               if (i, y) in points:
                    self.dfs(i, y, row, col, points)
以 C 的角度來看 points 不是全域變數根本不可能有用,但在 python 卻成功了
因為在 dfs() 這 function 裡的 points,若沒有特別賦予值的話,就是一個指標指到 call function 所傳入的變數

注意這對 string, int, tuple 無效

參考資料 :  python 新手初學

Related Posts:

  • Python List.pop(0) Python list.pop(0)      python 的 list 為 dynamic array,python.pop() default 值為 -1 python.pop()     # 時間複雜度 : O() python.pop(0)   # 時間複雜度 : O(n) Python deque.popleft() … Read More
  • Python UnitTest Unit Test      單元測試有一個通用模式 AAA原則,理解了就可以開始實作 Arrange   : 初始化物件、要用到的參數 Act   : 呼叫要測試的方法 Assert   : 驗證測試結果 Python Unit Test      unittest — Uni… Read More
  • Python 檢查 dict 的索引值是否存在 Check if a given key exists in a dict 要檢查 dictionary 是否存在索引值 直接查會直接 KeyError >>> d = {} >>> d['a'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'a' 這時就要靠 … Read More
  • Python 'a' + 1 = 'b'在 Python 3 實現  'a' + 1 = 'b' a = 'a' print(chr(ord(a)+1)) # b 參考資料 : https://stackoverflow.com/questions/12797067/how-can-i-do-a-1-b-in-python… Read More
  • Python Windows 換行符號與 Unix 換行轉換 ( convert CRLF to LF ) Convert CRLF to LF def convertCRLFtoLF(self, filename): WINDOWS_LINE_ENDING = b'\r\n' UNIX_LINE_ENDING = b'\n' with open(filename, "rb") as f: content = f.read() … Read More

0 意見:

張貼留言

Popular Posts