大量N个连续数字的Python和 [英] Python sum of N consecutive digits of a large number

查看:357
本文介绍了大量N个连续数字的Python和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在大范围内获得最大的连续数字 n

I need to get the largest sum of n consecutive digits in a range of a large number.

例如,范围可能是 5 ^ 150000 ,在此范围内,我想找出50,000个连续数字的最大和。

For example, the range could be 5^150000, within this range I want to find out the largest sum of 50,000 consecutive digits.

我使用两个循环的方法似乎永远不会终止。我将不胜感激。

The approach I have taken of using two loops seems to never terminate. I will appreciate any input.

代码:

count = 0
tempsum = 0
summ = 0                 # variables init
oldlist = ''
newlist = ''
num = str(3**2209) # for example

for digit in num: # go over all the digits in the number
    while count < 12 and len(num) >= 12 : # check in 12-digits blocks while possible
        oldlist += num[count] # update old list with new digit
        tempsum += int(num[count]) # add current digit to sum
        count += 1

    if tempsum > summ: # check if new sum is larger than old one
        summ = tempsum # update sum
        newlist = oldlist # update the sequence list
    oldlist = ''
    count = 0
    tempsum = 0
    num = num[1:] # slice the 'first' digit of the number

print(newlist, summ) # print sequence and desired sum


推荐答案

您不需要两个循环。

首先,让我们将所有数字放在列表中:

First, let's put all the digits in a list:

>>> a = list(map(int, str(5**150000)))

然后计算总和前50000个数字中的第一个:

Then calculate the sum of the first 50000 digits:

>>> maximum = current = sum(a[:50000])
>>> current
225318

现在,让我们遍历列表,从总和中删除最低位并在每次迭代过程中在前面加上下一个50000位数字:

Now, let's loop through the list, removing the lowest digit from the sum and adding the next one 50000 digits ahead during each iteration:

>>> for i in range(0, len(a)-50000):
...     current = current - a[i] + a[i+50000]

检查新的总和是否大于前一个总和,如果是,则将其设为新的临时最大值:

Check if that new sum is larger than the previous one, and if so, make it the new "interim maximum":

...     if current > maximum: maximum = current
...

一旦循环退出, maximum 包含最大值:

Once the loop exits, maximum contains the maximum value:

>>> maximum
225621

让我们将其全部放入函数中,这样就不会发生复制错误:

Let's put it all into a function, so no copying mistakes occur:

def maxdigitsum(number, digits):
    l = list(map(int, str(number)))
    maximum = current = sum(l[:digits])
    for i in range(0, len(l)-digits):
        current = current - l[i] + l[i+digits]
        if current > maximum: maximum = current
    return maximum

这篇关于大量N个连续数字的Python和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆