0

I am a bit of a beginner to recursion. Decided to dip my toes in the water by writing a recursive binary search program. Below is the code:

def midSplit(listo,element):

    halfSlice = (len(listo)-1)//2

    
    if len(listo) == 1 and listo[0] == element:
        return 'Element Found'

    elif len(listo) == 1 and listo[0] != element:
        return 'Not Found'


    if halfSlice < 1:
        return 'Not Found'

    if listo[halfSlice] > element:
        midSplit(listo[:halfSlice],element)

    elif listo[halfSlice] < element:
        midSplit(listo[halfSlice+1:],element)
    
    elif listo[halfSlice] == element:
        return 'Element Found'
    
    

print(
    midSplit(
    sorted([int(input('Enter an element: ')) for i in range(int(input('How Many Elements Do You Want Your List To Have?: ')))]),
    int(input('Pick The Element To Search For: ')))
    )

When I choose to input 3 elements, 12,24,25 and choose to search for 25, the function returns None? But how? When the function is first run, halfSlice would = 1, listo[halfSlice] = 24, and since 24 < 25,

elif listo[halfSlice] < element:
        midSplit(listo[halfSlice+1:],element)

will execute. This time the function will take listo[2] and 25 as the argument. Since the first if caluse in the function checks if the list argument is a single-element list, it will be true in this case right? len(listo) is INDEED 1, and listo[0] = 25 which is indeed the element.

So it should returns 'Element Found' right? But it instead returns None? Why?

Hash
  • 147
  • 1
  • 10
  • 1
    _"Why does my recursive function return None?"_, because you didn't `return` anything – Mulan May 01 '21 at 19:01
  • @Thankyou My question is why doesnt it return anything? The if clause at the beginning should execute and return 'Found' as it says there, once my list is down to one element right? – Hash May 01 '21 at 19:04

0 Answers0