0

I would like to implant recursive search using python, it will partition the upper part for the given key
example: list[2, 4, 6, 9, 10]
for the key is 6 case, the return index is 3
for the key is 4 case, the return index is 2
if the key is not in the list ie. the key is 7. It still needs to return with index 3 because 9 is greater than 7.
My code has issue to do recursive if the key is not in the array,
even I set boundary condition and I assume this will be ok, it cannot go through. Any advice is much appreciated.

def qReturn(alist, start, end, key):

    if key is 1:
        return 0
    mid = (start + end)//2
    if alist[mid] < key:
        return qReturn(alist, mid + 1, end, key)
    elif alist[mid] > key:
        return qReturn(alist, start, mid, key)
    if (start == end | end == mid | start > mid):
        return mid+1 
    else:
        return mid+1


alist = input('Enter the sorted list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))

index = qReturn(alist, 0, len(alist), key)
print('number q is at %d.' %index) 


For example list [2, 4, 6, 9, 10] and key is 7
The code can not be terminated


What kind of boundary condition I need to set and get the result for upper partition for 7?

1 Answers1

0
import numpy as np
alist = np.array([2, 4, 6, 9, 10])
key = 7
#index = qReturn(alist, 0, len(alist), key)
index_bin = (alist>key).argmax(axis=0).T
index_bin

output :

3

Recursive :

def splitAndCheck(leftside, rightside  ):

    if (rightside - leftside  <= 0):
      if (aList[rightside] >= key):
        return rightside
      else:
        return leftside
    middle = (leftside+rightside) //2
    if (aList[middle] >= key ):
      return splitAndCheck(leftside,middle)
    else:
      return splitAndCheck(middle+1,rightside)

print(aList) 
for key in range(20):
  print('key : ',key,'index : ',splitAndCheck(0,len(aList)-1))

output :

[ 2  4  6  9 10 12 14 18]
key :  0 index :  0
key :  1 index :  0
key :  2 index :  0
key :  3 index :  1
key :  4 index :  1
key :  5 index :  2
key :  6 index :  2
key :  7 index :  3
key :  8 index :  3
key :  9 index :  3
key :  10 index :  4
key :  11 index :  5
key :  12 index :  5
key :  13 index :  6
key :  14 index :  6
key :  15 index :  7
key :  16 index :  7
key :  17 index :  7
key :  18 index :  7
key :  19 index :  7
Hassan
  • 118
  • 6