您錯誤地報告了錯誤;它不會抱怨k
,它會抱怨smallerList
,因爲您定義了smallerlist
(小寫-1),然後試圖用大寫字母-L調用它。 Python變量區分大小寫,即smallerlist is smallerList == False
。在你的代碼
展望:
def quickSelect(lines, k):
if len(lines) != 0:
len(lst) != 0
是不地道; PEP-8說它應該只是lst
,如if lst:
。另外,camelCase是非細菌的;你的函數名應該是quick_select
。 lines
意味着你只能對文本進行操作,但是你的函數在任何可訂購的數據類型上都能正常工作,所以items
會更準確。你應該有一個文檔字符串,這樣下一個人就會知道它做了什麼,我們將再次調用len(items)
,所以我們不妨做一次並存儲結果。最後,如果k > len(items)
?
def quick_select(items, k):
"""
Return the k-from-smallest item in items
Assumes 0 <= k < len(items)
"""
num_items = len(items)
if 0 <= k < num_items:
pivot = items[num_items // 2]
繼續:
smallerlist = []
for i in lines:
if i<pivot:
smallerlist.append(i)
largerlist=[]
for i in lines:
if i>pivot:
largerlist.append(i)
你已經通過lines
重複兩次;你可以把它合併成一個單一的傳球。此外,更好的變量名:
smaller, larger = [], []
for item in items:
if item < pivot:
smaller.append(item)
elif item > pivot:
larger.append(item)
更好的變量名繼續,
num_smaller = len(smaller)
num_pivot = num_items - num_smaller - len(larger)
那麼你if
s爲亂序;它們更容易以讀取,所以
if k < num_smaller:
return quick_select(smaller, k)
elif k < num_smaller + num_pivot
return pivot
else:
return quick_select(larger, k - num_smaller - num_pivot)
然後什麼如果k < 0或k> =項數?:
else:
raise ValueError("k={} is out of range".format(k))
最後,因爲該函數是尾遞歸,很容易轉換爲迭代功能:
while True:
pivot = items[num_items // 2]
# ...
if k < num_smaller:
items = smaller
num_items = num_smaller
elif k < num_smaller + num_pivot
return pivot
else:
items = larger
num_items = num_larger
k -= num_smaller + num_pivot
...需要一些程序集,希望有所幫助!
請發佈您看到的任何錯誤的痕跡。並且請在你的問題中測試代碼,以確保它重現你在問題中描述的錯誤。 –
@bvidal:_不會修復問題文本中的錯誤! - - 它使其他人無法看到問題所在。 –
@HughBothwell:變量名中的拼寫錯誤不是帖子中引用的錯誤。從OP得到真正的錯誤實際上會有所幫助。 – bvidal