【发布时间】:2020-04-03 15:29:57
【问题描述】:
我正在尝试编写一个程序来解决这种模式并获取 nth 位置的值(n 从 1 到 10^5)
1,2,7,20,61,182...Reference
我能够编写一个函数来做到这一点。但继续获得
OverflowError: cannot convert float infinity to integer
py3 中出现较大 n 输入错误。 但它在 py2 中运行良好。
def getPattern(n):
total = 2
tmptotal = 1
count = 2
if(n == 1 or n == 2):
print(n)
else:
for i in range(2, n):
if(count == 2):
total = (total + (total/2))*2 + 1
count = 1
else:
total = (total + ((total-1)/2))*2
count = 2
tmptotal = total
return int(total)
n =int(input())
print(getPattern(n))
所以,我希望在 py3 环境中解决这个错误。
【问题讨论】:
-
您的代码对我有用,我只需将
if __name__ == '__main__':更改为def function():并在最后调用它,您的代码没有任何问题! -
对于n的哪个值,输出是无限的?
-
到目前为止,您的调试有何见解?
-
@backdor for n > 500 左右,我已经更新了问题..