分類

展開全部 | 收合全部

分類

展開全部 | 收合全部

【Leetcode】python – 利用 doctest 測試 leetcode python testcase 的優雅寫法 (doctest in class,搭配 class 的用法)

前言

這篇文章基本上內容會與我的另外一篇差不多,可以參考:

【Python 測試程式 #1】python 測試程式 – 利用 doctest 測試 python testcase 的優雅寫法,適用於 leetcode (doctest in function,搭配 function 的用法)

而這篇文章會更專注在 leetcode 的使用部分。(也會提到前一篇文章沒提到的在 class 中使用的部分)

  • 一樣的前言:

在 python 裡面,我們常需要在程式碼寫完時,測試程式碼功能是否正常,
「doctest」 這個套件雖然冷門,但使用時非常方便,這裡推薦給大家。

你可能會問,這好處在哪?

好處一 – 可以反覆測試不用靠手重新輸入

這應該是最重要的好處了吧,每次要測試只需要多下一個「-v」就行。
看看 leetcode 的那些測資,還有比只需要多下一個「-v」更方便的事情嗎?

好處二 – testcase 直接是註解,不用改code直接貼(欸?

我自己是覺得,他剛好把我們「不要的測試部分」都「用註解包起來了」,
整段 code 可以直接貼上去就能測試了,對懶人來說太方便了啦!

(當然,一個乾淨的code,最好不要有這種莫名其妙的註解啦……)

安裝

使用時我們需要先安裝「doctest」這個套件。
不過通常應該是都已經內建了。

我們可以用 import doctest 來測試看看有沒有 error。

import doctest

使用

在前面的文章中,我們提到了 doctest 在 function 中的基本用法。
這篇我們專門來講 doctest 在 class 中的用法。

範例一 – class 基本用法

class Test:
    """
    >>> a=Test(5)
    >>> a.multiply_by_2()
    10
    """
    def __init__(self, number):
        self._number=number

    def multiply_by_2(self):
        return self._number*2


if __name__ == "__main__":
    import doctest
    doctest.testmod()
  • 在這個例子裡面,當我們執行
python test.py -v
  • 會自動開始檢查:

當 a=Test(5) 時, a.multiply_by_2() 的值是否等於 10

範例二 – leetcode 中的 class 實戰

我們以 leetcode 的第一題為例:
https://leetcode.com/problems/two-sum/

如果想知道答案與詳解,可直接參考我的這篇文章,這邊只講用法:

【Leetcode】python – [1] Two Sum 個人解法筆記 (updated: 2022/04/06) | 內有 list comprehesion / dict comprehesion 整理

#
# @lc app=leetcode id=1 lang=python3
#
# [1] Two Sum

#  nums : List[int]
#  target: int

# List[int]

# @lc code=start

class Solution:
    """
    >>> a=Solution()
    >>> a.twoSum([2, 7, 11, 15], 9)
    [0, 1]
    """    
    def twoSum(self, nums, target): # 2 7 11 15
        my_dict = {}
        for idx, ele in enumerate(nums):
            rest = target - ele
            if rest in my_dict:
                return [my_dict[rest], idx]
            else:
                my_dict[ele] = idx # record


if __name__ == "__main__":
    import doctest
    doctest.testmod()

# @lc code=end
  • 在這個例子裡面,當我們執行
python test.py -v
  • 會自動開始檢查:

當 a=Solution() 時,輸入 a.twoSum([2, 7, 11, 15], 9),能不能正確回傳 [0, 1] 。

範例三 – 其實只是範例二的再更簡化

我們把範例二的 testcase 再改寫的簡單一點:

#
# @lc app=leetcode id=1 lang=python3
#
# [1] Two Sum

#  nums : List[int]
#  target: int

# List[int]

# @lc code=start

class Solution:
    """
    >>> Solution().twoSum([2, 7, 11, 15], 9)
    [0, 1]
    """    
    def twoSum(self, nums, target): # 2 7 11 15
        my_dict = {}
        for idx, ele in enumerate(nums):
            rest = target - ele
            if rest in my_dict:
                return [my_dict[rest], idx]
            else:
                my_dict[ele] = idx # record


if __name__ == "__main__":
    import doctest
    doctest.testmod()

# @lc code=end
  • 在這個例子裡面,當我們執行
python test.py -v
  • 會自動開始檢查:

當輸入 Solution().twoSum([2, 7, 11, 15], 9) 時,能不能正確回傳 [0, 1] 。

跟範例二相比,連暫時的 a 都不用宣告了! 越來越乾淨俐落了呢!

  • 此外,在範例三中,我更喜歡的是:

一行 input 與 一行 output,
正完美符合 leetcode testcase 的撰寫方式!

Reference

https://openhome.cc/Gossip/CodeData/PythonTutorial/AssertDocTest.html
https://ithelp.ithome.com.tw/articles/10244417
http://technology-sea.blogspot.com/2012/02/python-doctest-test-case.html
https://stackoverflow.com/questions/2708178/python-using-doctests-for-classes

⭐Python 基礎用法 相關文章整理⭐:
1.【Python】python list 清除, 移除內容元素 remove, pop, del, clear相關用法整理 sample code (內含範例程式碼)
2.【Python】寫模組 module、package 總整理 Importing files from different folder
3.【Python】python assert (斷言) 用法 sample code (內含範例程式碼)
4.【Python】python 一行 if else 語法 (one line if else) sample code (內含範例程式碼)
5.【Python】lambda 與 def function 使用方法與比較整理(內含範例程式碼)
6.【Python】python map 使用方法 與 其他寫法比較整理 (內含範例程式碼) sample code
7.【Python】python zip 使用方法 與 其他寫法比較整理 (內含範例程式碼) sample code
⭐Python 字串處理 相關文章整理⭐:
1.【Python】python print 變數的值 & 變數名稱 方法總整理
2.【Python】python string format str.format 總整理
⭐Python 檔案處理 相關文章整理⭐:
1.【Python】python 開關檔範例 與 程式模板 with open / file open sample code
2.【Python】取出檔案名稱 (含副檔名、不含副檔名) os path basename split 取出 檔名 路徑 不要副檔名 sample code
3.【Python】在 python 中利用 os.chmod 更改檔案的權限 chmod 777
4.【Python】利用 shutil 來複製檔案 shutil copy file
5.【Python】python 建立資料夾範例 mkdir os.makedirs() sample code
6.【Python】python 移除資料夾範例 rmdir shutil.rmtree() sample code
7.【Python】確認檔案是否存在 os.path.isfile / 確認資料夾是否存在 os.path.isdir sample code is folder / file exist
⭐Python 系統偵測 相關文章整理⭐:
1.【Python】python pyinotify sample code 偵測指定路徑底下的文件變化 (內有範例程式碼)
2.【Python】python 利用 argparse 使程式執行時可帶參數 (內附範例程式碼) sample code
⭐Python 平行運算 相關文章整理⭐:
1.【Python】threading – 建立多執行緒來執行程式 (內含範例程式碼) sample code
2.【Python】multiprocessing – 01 | 用多核心來執行程式 (內含範例程式碼) sample code
3.【Python】multiprocessing – 02 | pool, map, apply_async – 用多核心來執行程式並取得結果 (內含範例程式碼) sample code
4.【Python】python thread multiprocess 比較總整理
5.【Python】python pooling multiprocess – 用多核心來執行程式 sample code (內含範例程式碼)
⭐Python 測試程式 相關文章整理⭐:
1.【Python】python 測試程式 – 利用 doctest 測試 python testcase 的優雅寫法,適用於 leetcode (doctest in function,搭配 function 的用法)
2.【Leetcode】python – 利用 doctest 測試 leetcode python testcase 的優雅寫法 (doctest in class,搭配 class 的用法)
⭐Python Chatbot 相關文章整理⭐:
1.【Chatbot】(全圖文說明) LINE Developers bot 機器人註冊與設定
2.【Chatbot】(全圖文說明) ngrok 本地伺服器設定方法 – LINE bot local server
3.【Chatbot】Dialogflow API 串接 python 的方法 (內含範例程式碼)
4.【Chatbot】[講義分享] 手把手實作line機器人 (linebot API 運用)
⭐Python Google Colab (Colaboratory) 相關文章整理⭐:
1.【Colab】Python colab 上傳檔案的方法 (內含範例程式碼) upload files
2.【Colab】Python colab 連接 google 雲端硬碟取用資料 (內含範例程式碼) mount google drive
⭐Python 其他筆記 相關文章整理⭐:
1.【Python】anaconda 更新 (upgrade) python 3.8 版本筆記
2.【Sublime】Sublime 將縮排 “tab” 改成 4格空白 的方法 (圖文說明) sublime indent 4 spaces
3.【Sublime】Python 縮排小技巧 (很爛但實用) 快速將 tab 改成「4格空白」的方法
⭐【喜歡我的文章嗎? 歡迎幫我按讚~ 讓基金會請創作者喝一杯咖啡!
如果喜歡我的文章,請幫我在下方【按五下Like】 (Google, Facebook 免註冊),會由 「LikeCoin」 贊助作者鼓勵繼續創作,讀者們「只需幫忙按讚,完全不用出錢」哦!

likecoin-steps
Howard Weng
Howard Weng

我是 Howard Weng,很多人叫我嗡嗡。這個網站放了我的各種筆記。希望這些筆記也能順便幫助到有需要的人們!如果文章有幫助到你的話,歡迎幫我點讚哦!
另外,因為定位是「個人的隨手筆記」,有些文章內容「⚠️可能我理解有誤⚠️」或「?只寫到一半?」,如果有發現這樣的情況,歡迎在該文章的最下面留言提醒我!我會儘快修正或補上!感謝大家的建議與幫忙,讓網站能變得更好?

文章: 850

1 則留言

★留個言吧!內容有誤或想要補充也歡迎與我討論!