How does 'yield' work in this permutation generator?

前提是你 提交于 2019-12-04 12:12:46

It might help seeing a version that doesn't use generators:

def perm_generator(lst):
    res = []
    if len(lst) == 1:
        return [lst]
    else:
        for i in range(len(lst)):
            for perm in perm_generator(lst[:i] + lst[i+1:]):
                res.append([lst[i]] + perm)
    return res

gen = perm_generator([1,2,3])
print gen # prints [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

As you can see - this is not a "find and replace" of "return" with "yield". In the "return" version we needs to accumulate the result while in the "yield" version all that needs to be done is to "yield" the current permutation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!