为什么这段代码与11月13日14日分开?

时间:2017-02-21 20:07:34

标签: python python-3.x binary-search

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 个答案:

答案 0 :(得分: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