2015-10-26 34 views
-5
# find out a character in the given sorted list 
input_list = ['2', '6', '9', '11', '15', '30', '54'] 
input_char = raw_input('Enter a char: ') 

def bin_search(input_char): 
    start = 0 
    end = len(input_list) - 1 
    while start <= end:   
     mid = (start + end)/2  
     if input_char == input_list[mid]:   
      print 'Character ' + str(input_char) + ' found' 
      return input_char 
     elif input_char > input_list[mid]:    
      start = mid + 1 
     elif input_char < input_list[mid]:    
      end = mid - 1 
     else: 
      print 'Character not found' 
    return  

print bin_search(input_char)  
+3

你需要一个更具体的问题比“我做错了什么?”它应该做什么,它在做什么呢? – Barmar

回答

1

二进制搜索需要您正在搜索的列表进行排序。

由于值是字符串,名单目前尚未整理

>>> input_list = ['2', '6', '9', '11', '15', '30', '54'] 
>>> sorted(input_list) 
['11', '15', '2', '30', '54', '6', '9'] 

这将是最好的一切转换为数字,如果你的意思做一个数字搜索

+0

而开始<=结束: MID =(开始+端)/ 2 如果INPUT_CHAR ==排序(input_list [MID]): 打印 '字符' + STR(INPUT_CHAR)+ '发现' 返回INPUT_CHAR 类型错误:'int'对象不可迭代它显示错误 –