0

this is what i have done but this only locates one item in the list i want to print out both indices of item 36 please help this is what i have done so far if the way i posted this or my question isn't clear i apologize in advance [code]

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()
Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • It sounds like you're trying to find a range of indices in a sorted array. You can binary search until you find the item at index `i` and something that isn't the item at index `i + 1`. You can do this for the other (minimum) bound. – irrelephant Aug 13 '12 at 09:04

1 Answers1

0

You could make a function to handle this, and return a list of indicies instead of just one integer:

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
TheDude
  • 3,796
  • 2
  • 28
  • 51