2017-02-21 1 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 

Warum funktioniert das nicht nur für bestimmte Werte in der Liste, ich versuche, ein binäres Suchprogramm zu erstellen.Warum funktioniert dieser Code abgesehen vom 1. 11. 13. 14.?

+1

Was bedeutet nicht? Zeige ein Beispiel. –

+1

gibt es den Fehler Traceback (zuletzt letzten Aufruf): Datei "C: \ Benutzer \ Downloads \ Binary Search.py", Zeile 20, in fund = int (list1 [int (cal)]) IndexError: Listenindex außerhalb des Bereichs –

+1

Ich kann Ihre Gedanken nicht lesen. Bitte bearbeiten Sie Ihre Frage mit * allen * relevanten Informationen –

Antwort

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

Verwandte Themen