简体   繁体   中英

python string index out of range

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.

When python goes through a while loop, it waits until the end of the loop to check the exit criteria. It might be easier if you condense your function:

def isItIn(streen,carroter):
  while len(streen)>0:
    if streen[len(streen)/2]==carroter:
       return True
    if streen[len(streen)/2]>carroter:
       streen=streen[0:len(streen)/2]
    if len(streen)==0:return False
    if streen[len(streen)/2]<carroter:
        streen=streen[len(streen)/2+1:]

print isItIn('asdilk','a')
print isItIn('kdsoe','a')

Why don't you use str.index(sub\\[, start\\[, end\\]\\]) ? You can bet that it has an optimized implementation.

In [1]: s = "cddfggjkkqtwyy"

In [2]: s.index("d")
Out[2]: 1

In [3]: s.index("d") > -1
Out[3]: True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM