簡體   English   中英

遞歸函數中的Python yield語句問題?

[英]Python yield statement issue in recursive function?

現在,我學習如何在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

但是,我在window下的python shell中運行它,結果不正確。 只有四個結果。

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

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

在使用yield或程序時有什么問題嗎?

for val in permuteArr(arr, idx+1):循環for val in permuteArr(arr, idx+1):index + 1上替換idx + 1 index + 1

暫無
暫無

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

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