0
votes

I am trying to find a character in an alphabetized string... Here is the code

def isIn(char, aStr):

        middleChar = len(aStr)//2
        if char == aStr[middleChar]:
            return True
        elif char < aStr[middleChar]:
            LowerHalf = aStr[:middleChar]
            return isIn(char, LowerHalf)
        elif char > aStr[middleChar]:
            UpperHalf = aStr[middleChar:]
            return isIn(char, UpperHalf)
        else:
            return False

print(isIn('a', 'abc'))

It returns True. But When I put

print(isIn('d', 'abc'))

it returns this error: maximum recursion depth exceeded in comparison; instead of False.

I don't understand whats wrong. Please tell me where is the logical mistake I am doing.

2

2 Answers

0
votes

With d, The program splits the string from abc and picks out UpperHalf bc. Then it searches the new string bc. It then returns 'c' from 'bc' as expected. Since d > c, the program goes chooses that condition and once again returns the upper half of string 'c', which is c. Hence the recursion. To fix this, you need a separate way of handling length 1 strings.

0
votes

The last else is useless - it will never be executed.

The end of binary search is when the array becomes of one item - if this item isn't the searched one, the searched item isn't in the array.