Ok. So I am probably the most stupidest person on this planet, but can someone tell me why this gives me an error (The program is for searching a character in an alphabetically ordered string of characters using bisection search):
def isInIter(char, aStr):
print('char :'+char)
print('aStr :'+aStr)
isin = False
while(len(aStr) > 0):
if aStr[len(aStr)/2] == char:
isin = True
break
else:
if aStr[len(aStr)/2] > char:
aStr = aStr[0 : len(aStr)/2]
continue
if aStr[len(aStr)/2] < char:
aStr = aStr[(len(aStr)/2 + 1) :]
continue
return isin
Error:
isInIter('d','cddfggjkkqtwyy')
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-66-1de0eb4793fd> in <module>()
----> 1 isInIter('d','cddfggjkkqtwyy')
/home/user/Study/Ex/lec5_BisectionSearch.py in isInIter(char, aStr)
5 isin = False
6 while(len(aStr) > 0):
----> 7 if aStr[len(aStr)/2] == char:
8 isin = True
9 break
IndexError: string index out of range
But this works as expected:
char = raw_input('char :')
aStr = raw_input('aStr :')
isin = False
while(len(aStr) > 0):
if aStr[len(aStr)/2] == char:
isin = True
break
else:
if aStr[len(aStr)/2] > char:
aStr = aStr[0 : len(aStr)/2]
continue
if aStr[len(aStr)/2] < char:
aStr = aStr[len(aStr)/2 + 1 :]
continue
print isin
I appreciate your help.