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

Почему это не работает только для определенных значений в списке, я пытаюсь создать двоичную программу поиска.Почему этот код работает отдельно от 1-го 11-го 13-го 14-го?

+1

Что не работает в виду? Покажите пример. –

+1

есть ошибка Traceback (последний последний звонок): Файл «C: \ Users \ User \ Downloads \ Binary Search.py», строка 20, в fund = 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

 Смежные вопросы

  • Нет связанных вопросов^_^