【问题标题】:Python sum of N consecutive digits of a large number [closed]一个大数的N个连续数字的Python总和[关闭]
【发布时间】:2013-03-24 16:23:51
【问题描述】:

我需要在一个很大的数字范围内得到n连续数字的最大总和。

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

我使用两个循环的方法似乎永远不会终止。如有任何意见,我将不胜感激。

代码:

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

【问题讨论】:

  • 请向我们展示您的代码。
  • 重复:stackoverflow.com/questions/15300995/… 至少,它是基于同一个数学问题。我不明白为什么它被关闭为too localized。另一个关闭为not a real question。我认为这两种技术都足够通用,对后来的 SO-ers 有用。

标签: python algorithm numbers sum largenumber


【解决方案1】:

你不需要两个循环。

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

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

然后计算前50000位的总和:

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

现在,让我们循环遍历列表,从总和中删除最低位,并在每次迭代期间将下一个 50000 位添加到前面:

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

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

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

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

>>> maximum
225621

我们把它全部放到一个函数中,这样就不会出现复制错误了:

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

【讨论】:

  • 你可以检查你留下的数字是小于还是大于你得到的新数字,而不是对每一步求和。如果它更大,那么你计算新的最大值,否则你就继续
  • @elssar:那会丢弃我删除的which号信息,导致最终计算不正确。
  • 我认为你需要做new = new - a[i] + a[i+50000],否则你会得到一个不完全连续的数字总和。
  • 你是对的,@ThijsvanDien 找到了问题所在。我重命名了变量以使其更有意义并更正了逻辑。对不起。
  • @user2204926 好吧,那么您没有针对这种情况正确复制或修改它。该代码对我来说很好(输出 61)。
【解决方案2】:
#!/usr/bin/python
def maxSumOfNConsecutiveDigits(number,numberConsecutiveDigits):
    digits = [int(i) for i in str(number)]
    consecutiveSum = sum(digits[:numberConsecutiveDigits])
    largestSum = consecutiveSum
    for i in xrange(numberConsecutiveDigits,len(digits)):
        consecutiveSum += (digits[i]- digits[i - numberConsecutiveDigits])
        largestSum = max(largestSum, consecutiveSum)
    return largestSum
print maxSumOfNConsecutiveDigits(5**150000,50000)

【讨论】:

  • 一些更具描述性的变量名称不会有什么坏处。
  • 您确实需要至少为您的代码提供最少的 cmets。 (即使它们只是上述的琐碎案例。)
猜你喜欢
  • 1970-01-01
  • 2015-10-31
  • 1970-01-01
  • 2014-02-27
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
相关资源
最近更新 更多