如果我执行这段代码,它会部分工作。我尝试使用空字符串并且代码有效。但有时当字符在字符串中时它会告诉我 False!
def isIn(char, aStr):
"""char is a single character and aStr is
an alphabetized string.
Returns: true if char is in aStr; false otherwise"""
# base case: if aStr is an empty string
if aStr == '':
return('The string is empty!')
#return False
# base case: if aStr is a string of length 1
if len(aStr) == 1:
return aStr == char
# base case: see if the character in the middle of aStr is equal to the test char
midIndex = len(aStr)/2
midChar = aStr[midIndex]
if char == midChar:
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:])
aStr = str(raw_input('Enter a word: '))
char = str(raw_input('Enter a character: '))
print(isIn(char,aStr))