首页 > 解决方案 > Project Euler #8:使用 numpy 计算子列表的乘积返回负值

问题描述

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

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

麻木:

[..., 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))

输出 :

max multi_list: 2091059712
max multi_list_1: 23514624000

标签: pythonnumpymath

解决方案


默认情况下numpy.prod(),函数假定输入是 32 位整数,因此它输出 32 位整数,但在您的情况下,最大可能乘积是 9^13,它大于最大 32 位整数,因此您需要在函数中dtype提及。这边走 -numpy.int64numpy.prod()

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

推荐阅读