我执行了以下程序来生成连续数字列表。但是,对于列表中超过 70.000 个元素的计算似乎失败了。我尝试使用 Pycharm IDE 和 python 控制台。结果是一样的。我使用的是 Python 3.4.1 32 位版本。我应该怎么办 ?可能是哪个原因?
from pylab import *
a = 100000 # the number of elements from my_array
my_array = [i for i in range(a)]
missing_number = randint(a)
print('Generate a Random number: ', missing_number)
my_array.remove(missing_number) # We remove the random generated number from my_array
print('The number of elements of the list is: ', len(my_array)) #Length of my_array
print('the sum of the list is :',sum(my_array)) # Sum
sum02 = (a *(a-1)/2) # The sum of consecutive numbers
print('The complete sum of the consecutive numbers:',int(sum02),'\n')
print('And the missing number is:', int(sum02) - sum(my_array))
我将在我的机器上重现本地的结果:
C:\Util\Python34\python.exe "find_missing_number_2.py"
Generate a Random number: 15019
The number of elements of the list is: 99999
the sum of the list is : 704967685
The complete sum of the consecutive numbers: 4999950000
And the missing number is: 4294982315
Process finished with exit code 0
它不会导致错误。如您所见,它只是在进行错误的计算 如果比较两个变量: missing_number 与 int(sum02)-sum(my_array)
的结果最佳答案
from pylab import *
执行 from numpy import *
。这包括 numpy.sum该函数明确说明 Arithmetic 在使用整数类型时是模块化的,并且在溢出时不会引发错误。
为了避免这种情况,使用了内置的求和函数,如 Reut Sharabani 所示,或者不执行 from pylab import *
,无论如何这都是一种不好的做法。它可以在您不注意的情况下替换任何内置函数。据我所知,它目前至少取代了 sum 和 all,但我不确定就这些,你也不能确定它将来不会取代其他的。
关于Python大列表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27501389/