Search code examples
pythonlistsum-of-digits

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


I want to find consecutive digits in a string that sum to a given number.

Example:

a="23410212" number is=5 — output 23,41,410,0212,212.

This code is not working. What do I need to fix?

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 

Solution

  • This (sort-of) one-liner will work:

    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']
    

    This uses a nested generator expression over all possible slices and filters out the ones with the correct digit-sum. This is, of course, far from optimal (especially for long strings) because the inner loop should be stopped as soon as the digit-sum exceeds n, but should give you an idea.

    A more performant and readable solution would be a 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']
    

    Definitely read up on sum and map, as well.