我做了以下程序来生成连续数字列表。但是,对于列表中超过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)
答案 0 :(得分:3)
from pylab import *
执行from numpy import *
。这包括明确表示Arithmetic is modular when using integer types, and no error is raised on overflow.
为了避免这种情况,使用了内置求和函数,如Reut Sharabani所示,或者不使用from pylab import *
,这无论如何都是不好的做法。它可以替代任何内置函数,而无需您注意。据我所知,它至少取代了总和和所有,但我不确定这一切,你不能确定它不会取代其他人在将来。
答案 1 :(得分:0)
如果问题与列表大小相符,请尝试使用xrange:
# my_array = [i for i in range(a)]
my_array = xrange(a)
此外,如果您使用的是python 2.X,my_array = [i for i in range(a)]
与my_array = range(a)
相同
编辑:使用内置sum
(任意精确度):
__builtins__.sum(a)
答案 2 :(得分:0)
如何创建自己的函数来汇总连续数字......
def consecutive_sum(first, last):
half = (first + last) / 2.0
return half * (last - first + 1)
然后你不需要一个数字列表,你可以得到一个随机数(例如n)和......
sum1 = consecutive_sum(1, n-1)
sum2 = consecutive_sum(n+1, max_num)
答案 3 :(得分:0)
我发现原因是什么。 原因是user2313067提到了我导入了所有pylab模块的事实,并且它的一些功能与其他一些python内置函数重叠。确实导入所有模块的做法很糟糕,特别是如果你只使用一个函数。 所以在这种情况下解决方案是:
from pylab import randint
并且代码甚至适用于非常大的列表(a = 10000000)。 我的结果现在是正确的:
C:\Util\Python34\python.exe "find_missing_number_2.py"
Generate a Random number: 3632972
The number of elements of the list is: 9999999
the sum of the list is : 49999991367028
The complete sum of the consecutive numbers: 49999995000000
And the missing number is: 3632972
Process finished with exit code 0