我的代码将iMid读取为浮点并给出TypeError,即使将其包装在整数函数中也是如此。另外,还有另一种方法来查找中间值的索引,这比我在这里尝试的方法容易吗?
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
import numpy as np
def iMid(x):
'''
x : a string
returns: index of the middle value of the string
'''
if len(x) % 2 == 0:
return int(np.mean(len(x)/2, (len(x)+2)/2)) #wrapped the
# answer for iMid
#in the integer function
else:
return int((len(x)+1)/2)
if char == aStr[iMid] or char == aStr: #iMid is not being interpreted as an integer
return True
elif char < aStr[iMid]:
return isIn(char, aStr[0:aStr[iMid]])
else:
return isIn(char, aStr[aStr[iMid]:])
print(isIn('c', "abcd"))
最佳答案
在
if char == aStr[iMid] or char == aStr: #iMid is not being interpreted as an integer
iMid
不是整数。这是功能。您需要调用该函数以获取返回的整数。
if char == aStr[iMid(aStr)] or char == aStr: #iMid is called and returns an integer