Reputation: 48356
Now, I learn to how to use yield
in python program. so I want to implement word permutation
in 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
However, I run it in python shell under window, the results are not correct. There are only four results.
>>> for v in permuteArr(['a', 'b', 'c']):
print v
['a', 'b', 'c']
['a', 'c', 'b']
['b', 'a', 'c']
['c', 'b', 'a']
Is anything wrong when I use yield or in my program?
Upvotes: 1
Views: 153
Reputation: 1585
In loop for val in permuteArr(arr, idx+1):
replace idx + 1
on index + 1
Upvotes: 2