递归函数中的Python yield语句问题?

递归函数中的Python yield语句问题?,python,algorithm,yield,Python,Algorithm,Yield,现在,我学习如何在python程序中使用yield。所以我想在python中实现单词排列 def permuteArr(arr, index=0): '''(list, int) -> list Get all the permutation of the elements in list. >>> arr = ['a', 'b', 'c'] >>> for val in permuteArr(arr):

现在,我学习如何在python程序中使用
yield
。所以我想在python中实现
单词排列

def permuteArr(arr, index=0):
    '''(list, int) -> list

    Get all the permutation of the elements in list.
    >>> arr = ['a', 'b', 'c']
    >>> for val in permuteArr(arr):
            print val
    '''
    if index == len(arr):
        yield arr
    else:
        for idx in range(index, len(arr)):
            arr[idx], arr[index] = arr[index], arr[idx]
            for val in permuteArr(arr, idx+1):
                yield val
            arr[idx], arr[index] = arr[index], arr[idx]

if '__name__' == '__main__':
    arr = ['a', 'b', 'c']
    for val in permuteArr(arr, 0):
        print val
但是,我在窗口下的python shell中运行它,结果不正确。结果只有四个

>>> for v in permuteArr(['a', 'b', 'c']):
    print v

['a', 'b', 'c']
['a', 'c', 'b']
['b', 'a', 'c']
['c', 'b', 'a']

当我在我的程序中使用yield或时,有什么问题吗?

对于permuterar(arr,idx+1)中的val,在循环中
索引+1上替换
idx+1
为什么要递归执行此操作?看起来很awkward@PatrickCollins递归是解决此类问题的自然方法,因为置换的数量随着N的增加而增加!而且迭代方法很难推理(您希望能够编写N个嵌套循环,但不知道提前编写N个)。这就是说,此功能已经实现为
itertools.permutations