Python3报错:TypeError: ‘str‘ object cannot be interpreted as an integer:

Python3报错:TypeError: ‘str’ object cannot be interpreted as an integer:

问题描述:

在算法题目时,python3报错TypeError: ‘str’ object cannot be interpreted as an integer

class Solution():
    def numSection(self, n,array):
        s=0
        for l in range(n):
##            min_value,max_value=int('inf'),int('-inf')
            min_value,max_value=1000,0
            for r in range(l+1,n):
                max_value=max(max_value,array[r])
                min_value=min(min_value,array[r])
                if r-l==max_value-min_value:
                    s+=1
        return s+n        

if __name__ == "__main__":
    solution = Solution
    n=input()
    array=map(int,input().split())
    result = solution.numSection(solution,n,array)
    print(result)


原因分析:

原因是因为n=input()接收的值为字符串类型

解决方案:

解决方法很简单,只需要加n=int(n)即可

class Solution():
    def numSection(self, n,array):
    #加上下面这句即可
        n=int(n)
        s=0
        for l in range(n):
##            min_value,max_value=int('inf'),int('-inf')
            min_value,max_value=1000,0
            for r in range(l+1,n):
                max_value=max(max_value,array[r])
                min_value=min(min_value,array[r])
                if r-l==max_value-min_value:
                    s+=1
        return s+n
        
        





if __name__ == "__main__":
    solution = Solution
    n=input()
    array=map(int,input().split())
    result = solution.numSection(solution,n,array)
    print(result)

你可能感兴趣的:(python,leetcode,算法)