Python 程序找到等于数字 n 的连续数值的总和?

Python program find sum of consecutive number values equal to number n?

我想在字符串中找到总和为给定数字的连续数字。

示例:

a="23410212" 数字 is=5 — 输出 23,41,410,0212,212.

此代码无效。我需要修复什么?

def find_ten_sstrsum():
    num1="2825302"
    n=0;
    total=0;
    alist=[];
    ten_str="";
    nxt=1;
    for n in range(len(num1)):
        for n1 in range(nxt,len(num1)):
            print(total)
            if(total==0):
                total=int(num1[n])+int(num1[n1])
                ten_str=num1[n]+num1[n1]
            else:
                total+=int(num1[n1])
                ten_str+=num1[n1]
            if(total==10):
                alist.append(ten_str)
                ten_str=""
                total=0
                nxt+=1
                break
            elif(total<10):
                nxt+=1
     return alist 

这个 (sort-of) one-liner 可以工作:

def find_ten_sstrsum(s, n):
  return list(  # list call only in Python 3 if you don't want an iterator
    filter(
      lambda y: sum(map(int, y))==n, 
      (s[i:j] for i in range(len(s)) for j in range(i+1, len(s)+1)))
  )

>>> find_ten_sstrsum('23410212', 5)
['23', '41', '410', '0212', '212']

这使用嵌套的 generator expression over all possible slices and filters 和正确的 digit-sum。 当然,这远非最佳(特别是对于长字符串),因为一旦 digit-sum 超过 n,内部循环就应该停止,但应该给你一个想法。

一个更高效和可读的解决方案是 generator function:

def find_ten_sstrsum(s, n):
  for start in range(len(s)):
    for end in range(start+1, len(s)+1):
      val = sum(map(int, s[start:end]))
      if val > n:
        break
      if val == n:
        yield s[start:end]

>>> list(find_ten_sstrsum('23410212', 5))
['23', '41', '410', '0212', '212']

一定要仔细阅读 sum and map

您的功能有几个问题。最重要的是,您无法为其提供不同的数据来处理。你有它 hard-coded 来处理 一个 个特定的字符串,总共 10 个。你甚至在其中编写了带有 "ten" 的变量名,即使你的示例使用n=5。你的函数应该有两个输入参数:给定的字符串和 target sum.

注意:schwobaseggl 刚刚发布了一个可爱的 Pythonic 解决方案。但是,我会继续写这篇文章,以防您需要更接近您目前学习水平的功能。

您有多个逻辑路径,因此很难理解您是如何处理数据的。我推荐一种稍微不同的方法,这样你就可以干净利落地处理每个部分和:

for start in range(len(num1)):
    total = 0     # Start at 0 each time you get a new starting number.
    sum_str = ""
    for last in num1[start:]:
        print(total)
        # Don't create separate cases for the first and other additions.
        this_digit = num1[last]
        total += int(this_digit)
        ten_str += this_digit

        # If we hit the target, save the solution and
        #   start at the next digit
        if(total == target):
            alist.append(ten_str)
            break

        # If we passed the target, just
        #   start at the next digit
        elif(total > target):
            break

 return alist 

现在,这并没有解决相当你所有的问题,我还没有为你做一些会计工作(变量初始化, def 行等)。但是,我认为它会让您朝着正确的方向前进并保留代码的精神。