2013-11-14 51 views
1
def binary_search(li, targetValue): 
    low, high = 0, len[li] #error on this line 
    while low <= high: 
     mid = (high - low)/2 
     if li[mid] == targetValue: 
      return "we found it!" 
     elif li[mid] > targetValue: 
      low = mid - 1; 
     elif li[mid] < targetValue: 
      high = mid + 1; 
    print "search failure " 

最近剛發佈了這個問題,但我的代碼仍然不起作用?'builtin_function_or_method'對象不可自訂

+0

當len()是一個內置函數來計算一個對象的長度時,你不能寫'len [li]'。 –

回答

4

您使用了錯誤的括號len(li)len[li]

,當您試圖訪問你需要的,如果你使用[]你實際上是像訪問列表的順序使用function(args)功能記住。 your_list[index]。 len是內置函數,因此您需要()

+0

修好了,謝謝! – user2928929

2

Python使用(...)來調用函數,[...]來索引一個集合。此外,您正在嘗試做的是索引內置函數len

要解決此問題,使用括號而不是方括號:

low, high = 0, len(li) 
+0

它仍然不工作,因爲某些原因..它不會再給我一個錯誤,但它只是不輸出任何東西 – user2928929

+0

@ user2928929 - 你怎麼調用'binary_search'?你是否像使用'print binary_search(li,targetValue)'那樣使用'print'? – iCodez

+0

是的,即使我打印binary_search(li,targetValue),如果targetValue在列表中,它會返回「我們找到它」,但如果它不是它不會返回任何東西。 – user2928929

4

len是一個內置的功能,但你要使用它作爲一個序列:

len[li] 

撥打的功能代替:

len(li) 

請注意那裏的形狀改變,索引用方括號完成,調用完成圓括號。

0

花了我幾分鐘的時間才弄清楚是什麼錯誤。有時一個盲點阻止你看清楚。

錯誤

msg = "".join['Temperature out of range. Range is between', str(
      HeatedRefrigeratedShippingContainer.MIN_CELSIUS), " and ", str(
      RefrigeratorShippingContainer.MAX_CELSIUS)] 

正確

msg = "".join(['Temperature out of range. Range is between', str(
     HeatedRefrigeratedShippingContainer.MIN_CELSIUS), " and ", str(
     RefrigeratorShippingContainer.MAX_CELSIUS)]) 

正如你所看到的加入是一種方法,具有與()這是失蹤,導致該問題的調用。希望它可以幫助所有人查找方法並添加()。

相關問題