Python Program to Find Permutations of a String

1. Introduction

Finding all permutations of a given string is an interesting problem in the field of combinatorics. It's a common interview question and has real-world applications in problems like anagram solving, brute force password attacks, and more. Python's itertools module has a built-in function to generate permutations.

A permutation of a string is an arrangement of its characters in a different order. For a string of length n, there are n! (n factorial) possible permutations.

2. Program Steps

1. Import the itertools module, which includes permutation functionality.

2. Define the string for which permutations will be found.

3. Use itertools.permutations to generate all possible permutations of the string.

4. Iterate over the permutations and join them into strings.

5. Print out each permutation.

3. Code Program

from itertools import permutations

# Define the string
input_string = "ABC"

# Generate permutations using the permutations function from itertools
perm_list = permutations(input_string)

# Print each permutation
print("The permutations of the string are:")
for perm in perm_list:
    # Join the tuple of characters returned by permutations to form a string
    print(''.join(perm))

Output:

The permutations of the string are:
ABC
ACB
BAC
BCA
CAB
CBA

Explanation:

1. itertools.permutations is used to generate all possible permutations of input_string.

2. Each permutation is a tuple of characters, which is joined into a string with ''.join(perm).

3. The permutations are printed one by one inside the loop.

4. The words "The permutations of the string are:" are followed by each three-letter permutation of "ABC", indicating that the program has correctly generated all permutations.

Comments