【问题标题】:OverflowError: cannot convert float infinity to integer python3?OverflowError:无法将浮点无穷大转换为整数 python3?
【发布时间】: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 左右,我已经更新了问题..

标签: python algorithm sequence


【解决方案1】:

在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 2018-04-30
    • 2020-08-14
    相关资源
    最近更新 更多