代码将整数读取为

2024-06-22 22:28:46 发布

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

我的代码将iMid作为一个float读取,并给出一个TypeError,即使在将它包装到integer函数中之后也是如此。还有,有没有其他方法可以找到中间值的索引,比我在这里尝试的更简单

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

Tags: theantruestringlenreturnifis
3条回答

正如doctorlove所说,aStr[iMid]使用函数iMid作为索引。因为iMid是一个函数对象。 我认为你应该用aStr[iMid(aStr)]

你的问题是你在numpy mean函数中使用axis选项的方式。 https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.mean.html

根据经验,1-轴应该是整数,2-如果是元组,它应该在数组的维度内

例如,对于这样的数组:[1,2],轴只有0。如果有[[1,2]],则轴可以有0或1

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

相关问题 更多 >