開始使用免費開始

尋找元素

選對資料結構能大幅提升程式碼的效能。例如,當你要在資料中尋找特定元素時,可能需要在 listset 之間做選擇。在這個練習中,你會用 pytest 撰寫效能測試,比較在兩種資料結構(listset)上使用 in 運算子的速度。pytest 套件已經匯入。

本練習屬於課程

Python 測試入門

檢視課程

練習說明

  • 在測試函式中把 benchmark 當作引數傳入。
  • 接著在測試函式中呼叫 benchmark(),並將 find() 作為第一個引數傳入。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def create_list():
    return [i for i in range(1000)]
def create_set():
    return set([i for i in range(1000)])
def find(it, el=50):
    return el in it

# Write the performance test for a list
def test_list(____):
    ____(____, ____)

# Write the performance test for a set
def test_set(____):
    ____(____, ____)
編輯並執行程式碼