我的代碼將iMid讀取為浮點(diǎn)并給出TypeError,即使將其包裝在整數(shù)函數(shù)中也是如此。另外,還有另一種方法來(lái)查找中間值的索引,這比我在這里嘗試的方法更容易嗎?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貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
在
if char == aStr[iMid] or char == aStr: #iMid is not being interpreted as an integer
iMid
不是整數(shù)。這是功能。
您需要調(diào)用該函數(shù)以獲取返回的整數(shù)。
if char == aStr[iMid(aStr)] or char == aStr: #iMid is called and returns an integer

白豬掌柜的
TA貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
正如Doctorlove所說(shuō),aStr [iMid]正在使用函數(shù)iMid作為索引。因?yàn)閕Mid是一個(gè)功能對(duì)象。我認(rèn)為您應(yīng)該將所有aStr [iMid]替換為aStr [iMid(aStr)]
添加回答
舉報(bào)
0/150
提交
取消