我的鳕鱼没有回报

2024-04-26 17:55:09 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我执行这段代码,它会部分工作。我尝试了一个空字符串,代码可以工作。但有时当字符在字符串中时,它会告诉我错误!在

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))

Tags: ofthetestmiddlebasestringreturnif
2条回答

似乎您从未调用定义的函数:

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

演示:

^{pr2}$

Functions definition and execution:

The function definition does not execute the function body; this gets executed only when the function is called.

示例:

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

代码正确,应缩进:

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

然后测试:

^{pr2}$

顺便说一句,这句话可以用两行来表示:

def isIn(char, aStr):
    return char in sStr

相关问题 更多 >