【问题标题】:Why does this function return a long rather than an int?为什么这个函数返回一个long而不是一个int?
【发布时间】:2014-08-11 16:01:48
【问题描述】:

我已经定义了一个函数,它接受一个正整数作为输入并返回其数字的总和:

def digitSum(n):
    exp = 0
    digitSum = 0
    while n%(10**exp) != n:
        digitSum += (n%(10**(exp+1))-n%(10**(exp)))/(10**exp)
        exp += 1
    return digitSum

似乎如果 n

【问题讨论】:

  • 你为什么在乎?在 Python 3 中,long 无论如何都消失了,取而代之的是更智能的 int... 仅供参考,我会像这样重写你的函数:sum(map(int, str(n))) - 更具可读性,可能也更快。
  • 我不知道地图功能。谢谢!

标签: python types int long-integer return-type


【解决方案1】:

如果数字太大,Python int 转换为long。 你可以在这里读更多关于它的内容。

How does Python manage int and long?

(这种自动转换是 python 比 C/C++ 更消耗内存和更慢的原因之一,但这是另一个讨论)

>>> import sys
>>> x = sys.maxint             # set a variable to your systems maximum integer
>>> print type(x)
<type 'int'>                   # type is then set to int
>>> x += 1                     # if you increase it, it gets converted into long
>>> print type(x)
<type 'long'>

【讨论】:

  • 查看“太大”有多大:sys.maxint
  • 所以“问题”是当它最后一次计算 n%(10**(exp+1)) 时,除数很长。
【解决方案2】:

Python 2 区分了可以存储在机器底层 int 类型 (int) 中的整数和在语言中实现的任意精度整数 (long)。您不能强制您的函数返回 int(无论如何都不会引入溢出错误),因为当值太大而无法放入 int 时,Python 2 会自动创建一个 long 对象。

在 Python 3 中,从 Python 级别删除了区别:所有值都是 ints,无论大小如何,任何更精细的区别都是内置 int 类型的实现细节。

【讨论】:

    猜你喜欢
    • 2013-06-09
    • 2015-04-21
    • 1970-01-01
    • 2013-09-23
    • 2015-04-15
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    相关资源
    最近更新 更多