Skip to main content
 首页 » 编程设计

python之Python 列表中的二进制搜索

2025年05月04日9itcoder

<分区>

我正在尝试对 python 中的列表执行二进制搜索。列表是使用命令行参数创建的。用户输入他想在数组中查找的数字,然后返回元素的索引。由于某种原因,程序只输出 1 和 None。代码如下。 非常感谢任何帮助。

import sys 
 
def search(list, target): 
  min = 0 
  max = len(list)-1 
  avg = (min+max)/2 
  while (min < max): 
    if (list[avg] == target): 
      return avg 
    elif (list[avg] < target): 
      return search(list[avg+1:], target) 
    else: 
      return search(list[:avg-1], target) 
 
  print "The location of the number in the array is", avg 
 
# The command line argument will create a list of strings                                
# This list cannot be used for numeric comparisions                                      
# This list has to be converted into a list of ints                                      
def main(): 
 
  number = input("Please enter a number you want to search in the array !") 
  index = int(number) 
  list = [] 
  for x in sys.argv[1:]: 
    list.append(int(x)) 
  print "The list to search from", list 
 
  print(search(list, index)) 
 
if __name__ == '__main__': 
  main() 
 
CL : 
Anuvrats-MacBook-Air:Python anuvrattiku$ python binary_search.py 1 3 4 6 8 9 12 14 16 17 27 33 45 51 53 63 69 70 
Please enter a number you want to search in the array !69 
The list to search from [1, 3, 4, 6, 8, 9, 12, 14, 16, 17, 27, 33, 45, 51, 53, 63, 69, 70] 
0 
Anuvrats-MacBook-Air:Python anuvrattiku$