繁体   English   中英

欧拉计划 #8:使用 numpy 计算子列表的乘积返回负值

[英]Project Euler #8: Using numpy to calculate products of sublists returns negative values

我试图解决 Project Euler #8:在 1000 位数字中找到具有最大乘积的 13 个相邻数字。

我将整数列表分解为等长 13 的子列表,并计算每个子列表的乘积以找到最大值。 但是,使用 numpy.prod 与 math.prod 为我提供了不同的答案(math.prod 是正确的答案)。 经过仔细检查,从索引 88 numpy.prod 开始返回负值:

numpy:

[..., 78382080, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 371589120, -1322254336, 1857945600, -1817706496, 1651507200, 412876800, 294912000, ...]

数学:

[..., 78382080, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 371589120, 2972712960, 1857945600, 2477260800, 1651507200, 412876800, 294912000, ...]

我不确定为什么会这样,而且我无法在 numpy 文档中找到任何内容。

代码

p008_num.txt:

73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
import numpy
import math

f1 = open("p008_num.txt", "r").read()
n_list = list(map(int, list(f1)))
list_of_lists = [n_list[i:i+13] for i in range(len(n_list)-13)]

multi_list = [numpy.prod(num) for num in list_of_lists]
multi_list_1 = [math.prod(num) for num in list_of_lists]
# 23514624000

print("max multi_list:", max(multi_list))
print("max multi_list_1:", max(multi_list_1))

Output:

max multi_list: 2091059712
max multi_list_1: 23514624000

默认情况下numpy.prod() function 假设输入是 32 位 integer 所以它输出 32 位 integer 但你的情况下最大可能的产品是 9^13 这大于最大 32 位 88151097626 提到 dtype 所以你需要提到dtype numpy.int64numpy.prod() function 中。这样 -

multi_list = [numpy.prod(num, dtype=numpy.int64) for num in list_of_lists]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM