0

这就是我所做的,但这只在列表中找到一个项目我想打印出项目 36 的两个索引如果我发布这个的方式或我的问题不清楚,请帮助这是我到目前为止所做的我道歉提前[代码]

def main():

    mylist=[]
    for i in range(20):
        mylist.append(i*3)

    mylist.append(36)
    mylist.sort()
    print mylist
    binarySearch(mylist,0,len(mylist),36)

def binarySearch(thelist,lower,upper,item):

    if upper<lower:

        print 'item not in the list'
        return 

    middle=(lower+upper)/2

    if thelist[middle]<item:
        lower=middle+1
        binarySearch(thelist,lower,upper,item)

    elif thelist[middle]>item:
        upper=middle-1
        binarySearch(thelist,lower,upper,item)

    else: 
        print 'the item was found at index ',thelist[middle],middle
        return

main()
4

1 回答 1

0

您可以创建一个函数来处理这个问题,并返回一个索引列表而不是一个整数:

def check_for_number_around_index(index, sorted_list):
  indices = [index]
  i = index - 1
  while(i >= 0 and sorted_list[i] == sorted_list[index]):
    indicies.append(i)
    i = i - 1
  i = index + 1
  while( i < len(sorted_list) and sorted_list[i] == sorted_list[index]):
    indicies.append(i)
    i = i + 1
  return indicies
于 2012-08-13T17:50:02.683 回答