0

This code does a recursive bisection search for a character in a string.

When the print statements are not commented out, it seems to work well with the recursion and bisection, but the if statement that returns True does not seem to fire.

def isIn(char, aStr):
    '''
    char: a single character
    aStr: an alphabetized string

    returns: True if char is in aStr; False otherwise
    '''
    b = sorted(aStr)
    c = len(aStr)
    # print("string b " + str(b))
    # print("c " + str(c))
    # print("element middle: " + str(b[round(c/2)]))
    #print("char: " + str(char))
    #print(str(char) == str(b[round(c/2)]))
    if ((str(char) == str(b[round(c/2)]))): # this if statement does not seem to fire
        return True
    elif (c == 1 and char != str(b[round(c/2)])) or (c == 0 and char != "") :
        return False
        #print("false")
    else:

        #if str(char) == str(b[round(c/2)]):
         #   return True
           # print("true")
        if char > b[round(c/2)]:
            isIn(char, b[round(c/2):c])

        elif char < b[round(c/2)]:
            isIn(char, b[0:round(c/2)])
        else:
            return False
            #print('fales')
martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

1

You need to return the result of each recursive call.

This is a very common mistake, for some reason.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

You shouldn't be using round in whatever that calculation is, as then you are using a float instead of an int as the index to the string.
use int instead:

str(b[int(c/2)]))
Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60
0

This code works, has return before the recursive function calls:

def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string

returns: True if char is in aStr; False otherwise
'''
b = sorted(aStr)
c = len(aStr)
# print("string b " + str(b))
# print("c " + str(c))
# print("element middle: " + str(b[round(c/2)]))
#print("char: " + str(char))
#print(str(char) == str(b[round(c/2)]))
if ((str(char) == str(b[int(c/2)]))): # this if statement does not seem to fire
    return True
elif (c == 1 and char != str(b[round(c/2)])) or (c == 0 and char != "") :
    return False
    #print("false")
else:

    #if str(char) == str(b[round(c/2)]):
     #   return True
       # print("true")
    if char > b[round(c/2)]:
        return isIn(char, b[round(c/2):c])

    elif char < b[round(c/2)]:
        return isIn(char, b[0:round(c/2)])
    else:
        return False
        #print('fales')
  • You're going to have to change all of the `round` statements to `int`. It didn't occur to me, that you would only change the first one. And while you are editing please alter the last statement to `#print('fails')`. Just a mild annoyance. – Rolf of Saxony Sep 18 '16 at 16:07