2013-09-22 41 views
-3
nums = [734, 533, 449, 69, 869, 965, 656, 145, 913, 874, 987, 315, 967, 707] 
nums.sort() 
b=int(input("What number are you searching for?(Binary) ")) 
if b<nums[0] or b>nums[len(nums)-1]: 
    print("The number you entered it out of list range") 
    quit() 
while True: 
    if len(nums)==1 and nums[0]!=b: 
     print("The number has not been found") 
     break 
    mid=nums[len(nums)//2] 
    if mid==b: 
     print("The number has been found") 
     break 
    elif mid>b: 
     nums=nums[:len(nums)//2] 
    else: 
     nums=nums[len(nums)//2:] 

此二分查找有效,但我的老師說他不想讓我分片,我不知道這意味着什麼。需要幫助瞭解如何設置左右邊界。使用二進制搜索查找列表中的數字需要幫助

+0

'NUMS [:LEN(NUMS)// 2]'的切片。您的老師可能希望您使用兩個變量來保存上限和下限。 – Blender

+0

我剛剛添加了排序功能 – user2803415

+0

檢查了這一點:[二進制搜索(Python配方)](http://code.activestate.com/recipes/81188-binary-search/) –

回答

0

讓我要給你一個小提示

mid = (start + end) // 2 
if num[mid] > b: 
    end = mid