Posts

Showing posts from July, 2021

用 Mac 終端機操作 mongodb

寫筆記時的執行環境 MacOS Big Sur Version 11.4 MongoDB shell version v4.2.12 啟動資料庫 <path to binary>/mongod --dbpath <path to data directory> 參考資料: Install MongoDB 用 Mac 終端機連接資料庫 <path to binary>/mongo 操作指令 列出所有資料庫: show dbs 使用某個資料庫: use <db name> (沒設定的話預設是使用 test) 列出目前資料庫中的所有 collection: show collections 查詢目前資料庫中某個 collection 的資料: db.<collection name>.find({}) or db.<collection name>.find({}).pretty() (撈出來的資料會排版得好看一點) 在目前資料庫中某個 collection 裡新增一筆資料: db.<collection name>.insert({}) 在目前資料庫中某個 collection 裡新刪除符合條件的資料: db.<collection name>.remove({}) 最後更新日期:2021 年 8 月 9 日

[LeetCode] #698. Partition to K Equal Sum Subsets

題目 Given an integer array nums and an integer k , return true if it is possible to divide this array into k non-empty subsets whose sums are all equal. 直覺解 構想: 把 nums 加總後除以 k,算出每個 subsets 要達到的總和是多少。 要分成 k 個 subset,那就迭代 nums 四次。每次都從 nums[0] 開始迭代,迭代到的每個數,如果加進來不會超過 target,就把該數加進來,然後從 nums 裡把用過的數刪掉(用 for 迭代,一邊迭代一邊刪東西,會有元素在迭代過程中被跳過去,所以採用的方式是,沒被用到的數就加進去新陣列裡面,下次就迭代新陣列)。如果加到剛好等於 target,那就找到一個符合題目要求的 subset。 若符合題目要求的 subset 不足 k 個,就回傳 False。 python 3 實作(失敗): class Solution:     def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:         target, remainder = divmod(sum(nums), k)         if remainder != 0:             return False         subset_count = 0         for i in range(k):             total = 0             new_nums = []             for index, num in enumerate(nums):                 if total + num <= target:                     total += num                     if total == target:                         subset_count += 1      

程式設計相關社群、活動

網頁開發 網頁開發雜記 PJCHENder網頁開發咩腳 Backend 台灣 (Backend Tw) Taiwan Backend Group Backend.tw (友善版) Google Chrome Developers 語言 Python Taiwan JavaScript.tw Kotlin: Kraftsman:Coding 職人塾 資安 網路攻防戰 資安解壓縮 Infosec Decompress DEVCORE 如何成為駭客 (資安研討會、社群與網路資源篇) Cymetrics Tech Blog (有胡立大大) 台灣電腦網路危機處理暨協調中心 UCCU Hacker HITCON GIRLS 資安人科技網 個人或公司 資料科學家的工作日常 Ant Yi-Feng Tzeng 偷米騎巴哥 John Liu 的軟體工程思維 Will 保哥的技術交流中心 新加坡商鈦坦科技 Line 的技術部落格 區塊鏈李婷婷 、 FB 、 line 群 管理 TGONetworks 91 敏捷開發之路 技術管理者交流社團 課程 軟體開發學習資訊分享 Udemy 限時免費課程 cs50 中文討論區 Lidemy 鋰學院 商業思維學院 未分類 NEX Foundation 台灣未來基金會 iThome FB Daodu Tech 科技島讀 ∞ Lab 無限大實驗室.金融科技第一站 DevOps Taiwan Chatbot Developers Taiwan 軟體開發的疑難雜症交流區 年會 Hacks In Taiwan 台灣駭客年會 FB 台灣資安大會 cybersec 2021 開源人年會 COSCUP 2021 Python 年會 PyCon 2021 ModernWeb 開發者年會 2021 Javascript 開發者年會 FB: JSDC Taiwan 敏捷年會 Agile Summit 20

[LeetCode] #113. Path Sum II

題目 Given the root of a binary tree and an integer targetSum , return all root-to-leaf paths where each path's sum equals targetSum . A leaf is a node with no children. 直覺解 構想: 把所有 root-to-leaf paths 找出來(利用 recursion + DFS)後,一一檢查總和是否為 targetSum python 3 實作: from copy import deepcopy class Solution:     def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:         paths = []         if not root:             return paths         paths.append([])         paths = self.recursion(root, deepcopy(paths))         ans = []         for path in paths:             if sum(path) == targetSum:                 ans.append(path)         return ans     def recursion(self, root, paths):         if not root:             return []         for path in paths:             path.append(root.val)         if not root.left and not root.right:             return paths         paths_left = self.recursion(root.

flask 小抄(pip + virtualenv 版)(Flask 2.0.1)

初始化專案 建立並移動到專案資料夾 建立虛擬環境: pyenv exec python -m venv .venv 啟動虛擬環境: . .venv/bin/activate ,或 source .venv/bin/activate 安裝 Flask 套件: pip install Flask 在根目錄建立 app.py 設定環境變數: export FLASK_APP=app.py export FLASK_ENV=development (存擋後會自動重啟 app) .gitignore: Python.gitignore Application Factories  起手式: # app.py from flask import Flask, render_template, request def create_app():     app = Flask(__name__)     # do something     return app 執行專案 flask run 在瀏覽器網址列輸入 http://127.0.0.1:5000/ Jinja2 Builtin Filter 套件管理 requirements.txt 格式: Requirement Specifiers 、 Version specifiers 範例: EXAMPLE REQUIREMENTS FILE 列出已安裝的套件: pip freeze 連接資料庫 mongodb 安裝套件(先確定有啟動 venv): pip install pymongo or support for mongodb+srv:// URIs requires dnspython: pip install pymongo[srv] PyMongo 3.12.0 Documentation 連線設定:

[LeetCode] #124. Binary Tree Maximum Path Sum

題目 A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any path. 直覺解 構想: 像 53. Maximum Subarray 那樣,把累加的數字都存進去 current,確定數字真的有比較大才會放進 max_sum 當作答案。但是,Maximum Subarray 的題目,因為給的是陣列,只要從 array[0] 迭代到 array[-1] 一個單一方向就行,但是這一題的 tree 有兩個分支,而且頂多只有一個節點的左右節點都會在 path 裡,其他節點只會有左節點或右節點,情況跟 Maximum Subarray 很不一樣,腦袋已經轉不過來了。 python 3 實作(失敗): class Solution:     def maxPathSum(self, roo t: TreeNode) -> int:         max_sum = 0         current = -1000         return self.recursion(root, max_sum, current)     def recursion(self, root, max_sum, current):         if root is None:             return max_sum         if current + root.val < 0:      

[LeetCode] #518. Coin Change 2

題目 You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0 . You may assume that you have an infinite number of each kind of coin. The answer is guaranteed to fit into a signed 32-bit integer. 直覺解 構想: 像 70. Climbing Stairs 那樣,amount 對應到樓梯總共有幾階,coins 對應到不同的 step。 python 3 實作(失敗): class Solution:     def change(self, amount: int, coins: List[int]) -> int:         return self.coin_change(0, amount, coins)     def coin_change(self, curr, amount, coins):         if curr > amount:             return 0         if curr == amount:             return 1         result = []         for coin in coins:             result.append(self.coin_change(curr + coin, amount, coins))         return sum(result) 執行結果: Wrong Answer

在 Mac 上安裝 pyenv(python 版本管理工具)

安裝教學: Managing Multiple Python Versions With pyenv 執行完 curl https://pyenv.run | bash 後得到的指示: WARNING: seems you still have not added 'pyenv' to the load path. # (The below instructions are intended for common # shell setups. See the README for more guidance # if they don't apply and/or don't work for you.) # Add pyenv executable to PATH and # enable shims by adding the following # to ~/.profile: export PYENV_ROOT="$HOME/.pyenv" export PATH="$PYENV_ROOT/bin:$PATH" eval "$(pyenv init --path)" # If your ~/.profile sources ~/.bashrc, # the lines need to be inserted before the part # that does that. See the README for another option. # If you have ~/.bash_profile, make sure that it # also executes the above lines -- e.g. by # copying them there or by sourcing ~/.profile # Load pyenv into the shell by adding # the following to ~/.bashrc: eval "$(pyenv init -)" # Make sure to restart your entir

[LeetCode] #53. Maximum Subarray

題目 Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 直覺解 構想: 迭代所有可能的 contiguous subarray,找出最大的總和。 python 3 實作(失敗):     def maxSubArray(self, nums: List[int]) -> int:         max_sum = sum(nums)         length = len(nums)         for width in range(1, length):             star = 0             for star in range(length):                 if star + width <= length:                     result = sum(nums[star:star + width])                     if result > max_sum:                         max_sum = result         return max_sum 執行結果: Output Limit Exceeded Last executed input: [-64,78,56,10,-8,26,-18,47,-31,75,89,13,48,-19,-69,36,-39,55,-5,-4,-15,-37,-27,-8,-5,35,-51,83,21,-47,46,33,-91,-21,-57,0,81,1,-75,-50,-23,-86,39,-98,-29,69,38,32,24,-90,-95,86,-27,-23,-22,44,-88,3,27,9,55,-50,-80,40,5,-61,-82,-14,40,-58,35,93,-68,-26,94,3,-79,9,-88,21,19,-84,7

[LeetCode] #70. Climbing Stairs

題目 You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 參考 Solution 區的 java 解 Approach 1: Brute Force python 3 實作(失敗): class Solution:     def climbStairs(self, n: int) -> int:         return self.climb(0, n)     def climb(self, current_position, n):         if current_position > n:             return 0         elif current_position == n:             return 1         return self.climb(current_position + 1, n) + self.climb(current_position + 2, n) 執行結果: Time Limit Exceeded Last executed input: 38 Approach 2: Recursion with Memoization 自己的 python 3 實作: class Solution:     def __init__(self):         self.cache = {1: 1, 2: 2, 3: 3}     def climbStairs(self, n, current_position=0):         if current_position > n:             return 0         elif current_position == n:             return 1         elif se

[LeetCode] #207. Course Schedule

題目 There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1 . You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai . For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 . Return true if you can finish all courses. Otherwise, return false . 直覺解 構想: 為了加快尋找 prerequisites 的速度,整理一份 prerequisites 的 dictionary 版本。沒有 prerequisites 的課程一律算成 finished 的課程。 迭代所有課程,如果 prerequisites 都 finished 的話,該課程也算是 finished,如果檢查 prerequisites 的過程變成無限循環,就 return False。 python 3 實作(失敗): def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:     if not prerequisites:         return True     finished = {}     prerequisites_dict = {}     for _, [course, pre_requisi] in enumerate(prerequisites):         if not prerequisites_dict.get(course):             prerequisites_dict[

[LeetCode] #1091. Shortest Path in Binary Matrix

題目 Given an n x n binary matrix grid , return the length of the shortest clear path in the matrix. If there is no clear path, return -1 . A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0) ) to the bottom-right cell (i.e., (n - 1, n - 1) ) such that: All the visited cells of the path are 0 . All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner). The length of a clear path is the number of visited cells of this path. 直覺解 構想: 用遞迴。從 grid[0][0] 的點出發,按照「右下、下、右、左下、右上」的優先順序,依序嘗試下一個點要往哪個方向走,直到走到 grid[n-1][n-1] 或沒路了為止。 python 3 實作(失敗): def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:     ans = -1     n = len(grid)     if grid[n-1][n-1] != 0:         return ans     def findPath(current, ans):         i, j = current         if i >= n or j >=n:             return -1         if grid[i][j] != 0: