Python Program - Compute all the Permutation of the String
www.iigftidea.com
Here's a Python program to compute all the permutations of a given string using recursion:
def permute(s, start, end): if start == end: print(''.join(s)) else: for i in range(start, end + 1): s[start], s[i] = s[i], s[start] permute(s, start + 1, end) s[start], s[i] = s[i], s[start] string = input("Enter a string: ") n = len(string) s = list(string) permute(s, 0, n - 1)
Here, we define a function permute
that takes three arguments: the string to be permuted, the starting index, and the ending index. The if
statement checks if we have reached the end of the string, in which case we print the string. Otherwise, we iterate over the string and swap the characters at the start index and each subsequent index. We then call the permute
function recursively with the next index as the start index. After each recursive call, we swap the characters back to their original positions. Finally, we call the permute
function with the string, starting index of 0, and ending index of n-1
, where n
is the length of the string.