0

如果我执行这段代码,它会部分工作。我尝试使用空字符串并且代码有效。但有时当字符在字符串中时它会告诉我 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))
4

2 回答 2

5

看起来您从未调用过您定义的函数:

aStr = raw_input('Enter a word: ')  #raw_input already returns a string ,no need of str  
char = raw_input('Enter a character: ')
print isIn(char, aStr)                  #call the function to run it

演示:

Enter a word: foo
Enter a character: o
True

函数定义和执行:

函数定义不执行函数体;this 仅在调用函数时执行。

例子:

def func():   #function definition, when this is parsed it creates a function object
    return "you just executed func"

print func()    #execute or run the function
you just executed func           #output
于 2013-05-18T22:58:19.237 回答
0

你的代码是正确的,你应该缩进它:

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 == '':
    ...

然后只需测试:

>>> isIn('a', 'afdsf')
True
>>> print isIn('a', 'dfg')
False

顺便说一句,这在两行中完成了相同的操作:

def isIn(char, aStr):
    return char in sStr
于 2013-05-18T22:58:07.633 回答