Reputation: 35
Here in this quiz it tells me to write a code that make sure if a charachter is in a string which is sorted alphabetically and it tells me to bisection search to determine if a character is in a string and tells me to write a recursive code and not to use "in" (for i in ...)
My code was like that :
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
var = 0
if char == '' and aStr == '':
return True
elif char == '' or aStr == '' :
return False
elif aStr[int((len(aStr))/2)] == char :
return True
elif aStr[int((len(aStr))/2)] < char :
var = int((len(aStr))/2)
return isIn(char , aStr[var:])
elif aStr[int((len(aStr))/2)] > char :
var = int((len(aStr))/2)
return isIn(char , aStr[0 : var])
but when i pass values like (char = 'o' aStr = 'efggnqu', or char = 'y' aStr = 'orstv',or char = 'y' aStr = 'aamotv') it gives me an error like this :
Traceback (most recent call last):
File "submission.py", line 21, in isIn
return isIn(char , aStr[0 : var])
File "submission.py", line 18, in isIn
return isIn(char , aStr[var:])
File "submission.py"...OUTPUT TRUNCATED
what is the solution?
Upvotes: 2
Views: 253
Reputation: 868
Here's one fix:
def isIn(char, aStr):
var = len(aStr) // 2 #Pulled out for readability (and speed)
if char == '' and aStr == '':
return True
elif char == '' or aStr == '' :
return False
elif aStr[var] == char:
return True
elif aStr[var] < char:
return isIn(char, aStr[var + 1:])
elif aStr[var] > char:
return isIn(char, aStr[:var])
The crucial piece is the +1 on the third line up from the bottom. Without it, a single character is passed over and over again. 1 // 2
rounds down to 0, and "n"[0:]
is "n"
again.
Sample output:
>>> isIn("o", "efgnqu")
False
>>> isIn("y", "orstv")
False
>>> isIn("y", "aamotv")
False
>>>
Upvotes: 3