如果我执行这段代码,它会部分工作.我尝试了一个空字符串,代码工作.但有时它会在字符串中出现时告诉我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))
Run Code Online (Sandbox Code Playgroud)
看起来你从未调用过你定义的函数:
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
Run Code Online (Sandbox Code Playgroud)
演示:
Enter a word: foo
Enter a character: o
True
Run Code Online (Sandbox Code Playgroud)
函数定义不执行函数体; 只有在调用函数时才会执行此操作.
例:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
293 次 |
| 最近记录: |