簡體   English   中英

Python:遞歸生成器

[英]Python: recursive generator

我想遞歸地生成一串數字切片的所有可能總和。 例如:

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

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

但是,我編寫的代碼產生了生成器的生成器:

# 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]))

我該如何解決?

有時很難做到正確。 但是您通過添加額外的參數來混淆自己:

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

事實上:

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

您可以生成組合,然后使用functools.reduce

def slices(d, c = []):
  if not d:
     yield list(map(int, c))
  else:
     if c:
        yield from slices(d[1:], c[:-1]+[c[-1]+d[0]])
     yield from slices(d[1:], c+[d[0]])

import operator as op, functools
print([functools.reduce(op.add, i) for i in slices('891')][::-1])
#note: printing reverse of list to produce proper order of desired output

Output:

[18, 99, 90, 891]

要生成生成器的元素而不是生成器本身,請使用yield from

# 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 from rec(s[i:],c+int(s[:i]))
        #     ^^^^^^^^^^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM