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

时间:2014-06-16 04:19:55

标签: python algorithm yield

现在,我学会了如何在python程序中使用yield。所以我想在python中实现word permutation

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或在我的程序中有什么不对吗?

1 个答案:

答案 0 :(得分:2)

循环for val in permuteArr(arr, idx+1):替换idx + 1

上的index + 1