Skip to main content
 首页 » 编程设计

python之排列、迭代器、递归和双循环

2025年05月04日15dyllove98

这是一个迭代字符串中字母排列的函数:

def permutations(items): 
    for x in _permutations_rec('', items, len(items)): 
        yield x 
 
def _permutations_rec(current, items, n): 
    if len(current) == n: 
        yield current 
    else: 
        for item, other_items in pick_item(items): 
            for next_ in _permutations_rec(current+item, other_items, n): 
                yield next_ 
 
def pick_item(items): 
    for i, item in enumerate(items): 
        yield item, items[:i] + items[i+1:] 
 
# print permutations 
for x in permutations('abc'): 
    print x 

在 else 部分的 _permutations_rec 中,我有两个循环。在第一个我 选择我附加到 current 字符串的下一个项目。第二个循环 迭代下一个部分结果并产生它们。所以,第二个 for 只是为了 处理递归调用的迭代器并“冒泡”其结果。 当递归调用产生结果时,我经常发现这种模式,例如使用 backtracking 时.

问题:

是否有一种惯用的、优雅的方式只使用一个循环而不是两个?虽然我知道这两个循环没有任何问题,但也许有一些迭代器功夫可以让我只使用一个(越简单越好)。

编辑:

  • 我知道 itertools.permutations,我的 permutations 只是一个玩具示例

请您参考如下方法:

在现代 Python 中,您可以使用 yield from以避免最内层循环。是时候升级了吗? :^)

    for item, other_items in pick_item(items): 
        yield from _permutations_rec(current+item, other_items, n)