Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to find all permutations of a string - Python Program

Example 1 :

def permutations(s): """Generate permutations recursively.""" if len(s) == 1: return [s] perms = [] for i in range(len(s)): for p in permutations(s[:i] + s[i+1:]): perms.append(s[i] + p) return perms print(permutations("abc"))

Output

 
OUTPUT  :
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Example 2 : Advanced Program

def get_permutations(s): """ Recursively generates all permutations of a given string. Args: s: The input string. Returns: A list containing all permutations of the string. """ # Base case: if the string has 0 or 1 character, it's already a permutation if len(s) <= 1: return [s] permutations = [] # Iterate through each character in the string for i, char in enumerate(s): # Create the remaining string by excluding the current character remaining_chars = s[:i] + s[i+1:] # Recursively get permutations of the remaining characters for sub_permutation in get_permutations(remaining_chars): # Prepend the current character to each sub-permutation permutations.append(char + sub_permutation) return permutations # Example Usage: input_string = "abc" all_permutations = get_permutations(input_string) print(f"All permutations of '{input_string}':") for p in all_permutations: print(p) # Another example input_string_2 = "dog" all_permutations_2 = get_permutations(input_string_2) print(f"\nAll permutations of '{input_string_2}':") for p in all_permutations_2: print(p)

Output

 
OUTPUT  :
All permutations of 'abc':
abc
acb
bac
bca
cab
cba

All permutations of 'dog':
dog
dgo
odg
ogd
gdo
god