Program Overview
This Python program generates all permutations of a given string. A permutation of a string is a rearrangement of its characters. The program utilizes recursion to explore all possible arrangements and prints each unique permutation.
Program Structure
- Function Definition: The main function,
permute(s)
, is defined to generate permutations of the strings
. - Base Case: If the string is empty, return a list containing an empty string.
- Recursive Case: Iterate through each character in the string, fixing one character at a time and recursively generating permutations of the remaining characters.
- Combining Results: Combine the fixed character with the permutations of the remaining characters to form new permutations.
- Output: Print all unique permutations.
Python Code
def permute(s):
"""
Generate all permutations of a string.
Args:
s (str): The input string for which permutations are to be generated.
Returns:
list: A list containing all unique permutations of the input string.
"""
# Base case: if the string is empty, return a list with an empty string
if len(s) == 0:
return [""]
# List to store all permutations
permutations = []
# Iterate through each character in the string
for i in range(len(s)):
# Fix the current character
current_char = s[i]
# Get the remaining characters after fixing the current character
remaining_chars = s[:i] + s[i+1:]
# Generate all permutations of the remaining characters
for p in permute(remaining_chars):
# Combine fixed character with permutations of the remaining characters
permutations.append(current_char + p)
return permutations
# Example usage
if __name__ == "__main__":
input_string = "abc"
result = permute(input_string)
print("All permutations of the string '{}':".format(input_string))
for perm in result:
print(perm)
How to Run the Program
To run the program, follow these steps:
- Ensure you have Python installed on your system.
- Copy the code into a file named
permutations.py
. - Open a terminal and navigate to the directory where the file is saved.
- Run the program using the command:
python permutations.py
. - The output will display all unique permutations of the specified string.
Conclusion
This program effectively generates all permutations of a string using a recursive approach. The simplicity of the code allows for easy understanding and modification to suit various needs. By experimenting with different input strings, users can explore the full range of permutations available.