2017-02-21 7 views
-1
print('This is a binary search!') 
list1 = [1,3,6,9,12,23,67,68,69,71,74,86,95,100] 

find = int(input('Which item would you like to find?')) 

found = 0 

def half(value): 
    if value % 2 == 1: 
     value = (float(value)/2) + 0.5 
     return int(value) 
    else: 
     return int(value/2) 

length = len(list1) 
cal = half(length) 
pal = 0 
while found == 0: 
    fund = int(list1[int(cal)]) 
    if int(fund) == find: 
     print(str(cal + 1) + ' is the reference!') 
     found = 1 
    if fund > find: 
     cal = half(cal) 
    if fund < find: 
     cal = half(cal) + cal 

なぜ、これがリストの特定の値に対してのみ機能しないのですが、バイナリ検索プログラムを作成しようとしています。なぜこのコードは第11回第13回第14回から離れて動作しますか?

+1

どういう動作しませんか?例を示します。 –

+1

エラーがあります トレースバック(最新のコール最後): ファイル "C:\ Users \ User \ Download \ Binary Search.py​​"、行20、 ファンド= int(list1 [int(cal)]) IndexError:リストのインデックスが範囲外になっています –

+1

私はあなたの心を読むことができません。 *すべての関連情報を使用して質問を編集してください –

答えて

0
print('This is a binary search!') 
list1 = [1,3,6,9,12,23,67,68,69,71,74,86,95,100] 

find = int(input('Which item would you like to find?')) 
#This shows that the program has not found the number. 
found = 0 
#This function finds half of the value. 
def half(value): 
    return value // 2 
#This fidns the length of the list. 
length = len(list1) 
#This is the starting middle value. 
cal = half(length) 
#This is the lower bound. 
pal = 0 
#This is the upper bound. 
sal = len(list1) 
#This makes a limit for if the item is not in the list. 
gal = 2*(len(list1)) 
#This keeps track of how many times the while loop is triggered. 
mal = 0 
#This makes it keep trying. 
while found == 0: 
    #This clocks the amount of times the while loop is triggered. 
    mal = mal + 1 
    #This retrieves the value from the list. 
    fund = int(list1[int(cal)]) 
    #If fund is find then it has found the element. 
    if int(fund) == find: 
     #This print the place in the list.clear 
     print(str(cal + 1) + ' is the reference!') 
     #This ends the while loop. 
     found = 1 
    #This checks if it is lower than the guess. 
    if fund > find: 
     #It brings down the upper bound. 
     sal = cal 
    #This checks if it is higher than the guess. 
    if fund < find: 
     #This brings up the lower bound. 
     pal = cal 
    #This adjusts cal. 
    cal = half(sal + pal) 
    #This stops the program after a number of attempts. 
    if mal > gal: 
     #This tells the user that it is not in the list. 
     print('Your number is not in the list!') 
     #This ends the while loop. 
     found = 1 

WOO

関連する問題