算法----练习题2

思路:

  方法一:

    固定一个值,然后再列表里里依次选择数进行查找

 

def choice(data_set,val):
   for i in range(len(data_set)):
       if data_set[i] > val:
           continue
       for j in range(i + 1,len(data_set)):
           if data_set[i] + data_set[j] == val:
               return (i,j)

data_set = [1,2,5,4]
print(choice(data_set,3))

结果显示为:

  方法二:

    利用二分查找法,数值的和减去依次查找的数值,然后再列表里查找商

import copy

def bin_search(data_set,val,low,high):
    while low <= high:
        mid = (low + high) // 2
        if data_set[mid] == val:
            return  mid
        elif data_set[mid] > val:
            high =mid - 1
        else:
            low =mid + 1
    return

def choice_2(data_set,target):
    data_set_1 = copy.deepcopy(data_set)
    data_set_1.sort()
    print(data_set_1)
    for i in range(len(data_set_1)):
        a = i
        b = bin_search(data_set_1,target - data_set_1[a],i + 1,len(data_set_1) - 1 )
        if b:
            return (data_set.index(data_set_1[a]),data_set.index(data_set_1[b]))

data_set = [1,2,5,4]
print(choice_2(data_set,3))

 结果显示为:

 

posted @ 2018-06-25 10:15  追风的小蚂蚁  阅读(337)  评论(0编辑  收藏  举报