gpt4 book ai didi

python - python系列中最大的产品

转载 作者:太空狗 更新时间:2023-10-29 23:58:07 25 4
gpt4 key购买 nike

1000 位数字中具有最大乘积的四个相邻数字是:

9 × 9 × 8 × 9 = 5832

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

找出 1000 位数字中具有最大乘积的 13 个相邻数字。这个产品的值(value)是多少?

我对这个问题的解决方案是:

def no(x):
previous=0
i=0
t=1
while i !=987:
for num in x[i:i+13]:
no=int(num)
t=no*t

if t>previous:
previous = t
i=i+1
t=1
return previous

还有其他好的有效方法可以解决这个问题吗?因为我觉得我的效率不是很高

最佳答案

您可以在 max 函数中使用生成器表达式和适当的 key 函数来计算子数字的乘积。为此,您可以使用 map 函数将数字转换为整数,并使用 reduce(在 python 3.X functools.reduce 中)计算整数的乘积。

>>> max((digits[i:i+13] for i in xrange(0, len(digits) - 12)), key=lambda x: reduce(mul, map(int, x)))
'5576689664895'

请注意,如果您的数字之间有换行符,您需要使用 str.replace() 方法将其删除。

digits = digits.replace('\n', '')

更优化的方法:

由于您每次都处理 13 位数字,因此您可以使用容器以便在每次迭代中保留您的数字,这里最好的选择是 deque() 形式 collections 模块,maxlen=13 弹出和推送操作的顺序是 O(1)。然后您可以计算前 13 位数字的乘积,并且在每次推送和弹出时,您的初始乘积应除以弹出的项目,并乘以推送的项目。在每次迭代中,您可以只保留具有最大乘积的序列。

from operator import mul
from collections import deque
from copy import copy

def cal_max_prod(container, current_product):
max_container = {'seq': copy(container), 'prod': current_product}
for i in digits[13:]:
popped_item = int(container.popleft())
container.append(i)
try:
push_item = int(i)
current_product = (current_product / popped_item) * push_item
except ZeroDivisionError:
if '0' not in container:
current_product = reduce(mul, map(int, container))
else:
if current_product > max_container['prod']:
max_container['prod'] = current_product
max_container['seq'] = copy(container)

return ''.join(max_container['seq'])

演示:

container = deque(digits[:13], maxlen=13)
current_product = reduce(mul, map(int, container))
print cal_max_prod(container, current_product)
5576689664895

关于python - python系列中最大的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35501967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com