So I'm taking a python class online. I would like help spotting the differences between my code and the correct answer code. I didn't annotate mine but the answer is annotated and every thing you need should be there to figure out what I'm trying to do. I wrote my answer independently at first and it turns out to be pretty similar to the correct answer code given by the class. However, my code keeps returning the error
Traceback (most recent call last):
File "submission.py", line 11, in isIn
middle = aStr[midIndex]
IndexError: string index out of range
Here is my code
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
midIndex = len(aStr)//2
middle = aStr[midIndex]
if len(aStr) == 0:
return False
if len(aStr) == 1 or char == middle:
return True
else:
if char > middle:
return isIn(char,aStr[:middle])
else:
return isIn(char,aStr[middle +1:])
here is the correct answer given to me by the class:
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Base case: If aStr is empty, we did not find the char.
if aStr == '':
return False
# Base case: if aStr is of length 1, just see if the chars are equal
if len(aStr) == 1:
return aStr == char
# Base case: See if the character in the middle of aStr equals the
# test character
midIndex = len(aStr)//2
midChar = aStr[midIndex]
if char == midChar:
# We found the character!
return True
# Recursive case: If the test character is smaller than the middle
# character, recursively search on the first half of aStr
elif char < midChar:
return isIn(char, aStr[:midIndex])
# Otherwise the test character is larger than the middle character,
# so recursively search on the last half of aStr
else:
return isIn(char, aStr[midIndex+1:])
midIndex
for my code is middle_nummber
and midChar
for my code is just middle
.