Search code examples
pythonrecursiongenerator

Python: recursive generator


I want to recursively generate all the possible sums of the slices of a string of digits. For example:

Input: '891'
Output: 18, 99, 90, 891

In details:
    8+9+1 = 18
    8+91 = 99
    89+1 = 90
    891 = 891

However, the code I wrote yields generators of generators:

# s: string of digits, c: sum of slices
def rec(s,c):
    for i in range(1,len(s)+1):
        if s=='': yield c
        else: yield rec(s[i:],c+int(s[:i]))

How can I fix it?


Solution

  • It can sometimes be tricky to get right. But you are confusing yourself by adding the extra argument:

    def rec(s):
        # No split.
        yield int(s)
    
        # Split.
        for i in range(1, len(s)):
            left = int(s[:i])
            for right in rec(s[i:]):
               yield left + right
    

    And indeed:

    >>> list(rec("891"))
    [891, 99, 18, 90]