I was writing a program to generate all the permutations of a string:
def print_permutations_wrapper(str):
strList = str.split()
print_permutations(strList, 0, len(strList))
def print_permutations(strList: list, start: int, end: int):
if start >= end - 1:
print(strList)
return
print_permutations(strList, start+1, end)
for i in range(start+1, end):
strList[start], strList[i] = strList[i], strList[start]
print_permutations(strList, start+1, end)
strList[i], strList[start] = strList[start], strList[i]
def main():
str = 'a b c'
print_permutations_wrapper(str)
if __name__ == "__main__":
main()
Its working correctly, but rather than printing it, I wanted to return it lazily using yield
:
def print_permutations_wrapper(str):
strList = str.split()
yield from print_permutations(strList, 0, len(strList))
def print_permutations(strList: list, start: int, end: int):
if start >= end - 1:
yield strList
return
yield from print_permutations(strList, start+1, end)
for i in range(start+1, end):
strList[start], strList[i] = strList[i], strList[start]
yield from print_permutations(strList, start+1, end)
strList[i], strList[start] = strList[start], strList[i]
def main():
str = 'a b c'
x = print_permutations_wrapper(str)
print(list(x))
if __name__ == "__main__":
main()
The output that I get is:
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
rather than all the permutations.
How to correct this?
I am using Python 3.7.