2016-03-03 117 views
1

我試圖創建一個二進制搜索線性搜索不工作

L = [0, 1, 2]; X= 3;i=0 
while (L[i]!= X)and (i < len(L)): 
    i = i+1 
if i==len(L): 
    print('Not here!') 
else: 
    print(X, 'at position', i) 

,但有一個問題,我的while循環,並用IndexError。任何幫助將不勝感激。

+1

1.縮進'if'塊以匹配'while'塊2.交換條件,和(L [i]!= X)' –

回答

3

and聲明是short-circuit operator,因此它只評估RHS上的參數,如果LHS上的參數爲True。在你的情況下,這會產生索引錯誤。交換條件的順序和你的代碼將完美地工作:

L = [0, 1, 2]; X= 3;i=0 
while (i < len(L)) and (L[i]!= X): 
    i = i+1 
    if i==len(L): 
     print('Not here!') 
    else: 
     print(X, 'at position', i)