我写了一些代码,在给定n个数的情况下,找出要计数到1的最小事件数
class Solution(object):
def __init__(self):
events=0
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
if n==1 or not n:
return self.events
if n%2==0:
self.events=self.events+1
self.integerReplacement(self,n/2)
else:
self.events=self.events+1
self.integerReplacement(self,(n-1)/2)
return self.events
def stringToInt(input):
return int(input)
def intToString(input):
if input is None:
input = 0
return str(input)
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
line = lines.next()
n = stringToInt(line)
ret = Solution().integerReplacement(n)
out = intToString(ret)
print out
except StopIteration:
break
if __name__ == '__main__':
main()
我得到的错误是
Finished in N/A
AttributeError: 'Solution' object has no attribute 'events'
Line 12 in integerReplacement (Solution.py)
Line 38 in main (Solution.py)
Line 46 in <module> (Solution.py)
我不知道为什么它不能识别我在init函数中声明的events变量。我做错什么了
它需要是实例变量
self
的一个属性,因此更改:收件人:
正如Cireo所说,您需要使用:
self告诉python声明的变量必须可供整个类访问。否则,它只能在函数的本地范围内访问。换句话说,event和self.event是两个独立的变量
或者,如果您出于任何原因想使用events=0,您想使它成为一个class属性,那么您当前的代码就可以工作了。为此,请删除\uuu init \uuuu函数并声明变量:
相关问题 更多 >
编程相关推荐