我的代码将iMid读取为浮点并给出TypeError,即使将其包装在整数函数中也是如此。另外,还有另一种方法来查找中间值的索引,这比我在这里尝试的方法更容易吗?def isIn(char, aStr):'''char: a single characteraStr: an alphabetized stringreturns: True if char is in aStr; False otherwise'''# Your code hereimport numpy as npdef 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 Trueelif char < aStr[iMid]: return isIn(char, aStr[0:aStr[iMid]]) else: return isIn(char, aStr[aStr[iMid]:])print(isIn('c', "abcd"))
3 回答

呼如林
TA贡献1798条经验 获得超3个赞
在
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

白猪掌柜的
TA贡献1893条经验 获得超10个赞
正如Doctorlove所说,aStr [iMid]正在使用函数iMid作为索引。因为iMid是一个功能对象。我认为您应该将所有aStr [iMid]替换为aStr [iMid(aStr)]
添加回答
举报
0/150
提交
取消