![](/img/trans.png)
[英]How to fix this python error? OverflowError: cannot convert float infinity to integer
[英]OverflowError: cannot convert float infinity to integer python3?
我正在尝试编写一个程序来解决这种模式并获得第 n 个位置的值( n 从 1 变化到 10^5 )
1,2,7,20,61,182...参考
我能够写一个 function 来做到这一点。 但不断获得
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 env 中解决这个错误。
在 python3 /
中是浮点除法,因此您的total
变量被制成浮点数。 python3 中的 python2 代码的等效代码是这样的:
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 total # No cast needed
n = int(input())
print(getPattern(n))
$ python3 a.py
1000
330517704870201659222613814938036091491355508188037041916230092056707149336676224885194578462652015490977444424218145588987738645525154727966335681314488418506905056299580200969503693557241210318597600029397154510282236953905773609515391543263521668622626544531370086101386763599259723954366342063729034055207567140944645572557104099576971974229639101021224734402343310542961589984673879191254735147027265106522417859716025703587596412186791458002653591533043275692225713805000
$ python2 a.py
1000
330517704870201659222613814938036091491355508188037041916230092056707149336676224885194578462652015490977444424218145588987738645525154727966335681314488418506905056299580200969503693557241210318597600029397154510282236953905773609515391543263521668622626544531370086101386763599259723954366342063729034055207567140944645572557104099576971974229639101021224734402343310542961589984673879191254735147027265106522417859716025703587596412186791458002653591533043275692225713805000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.