[英]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.