Question

How can I count the number of ways to rearrange a word in Python?

Answer and Explanation

Counting the number of ways to rearrange a word in Python involves calculating permutations, while also handling cases with repeating characters. Here's a breakdown of how to do it:

1. Permutations without repetitions: If a word has all unique characters, the number of rearrangements is simply the factorial of the length of the word. For example, the word "CAT" can be rearranged in 3! = 3 2 1 = 6 ways.

2. Permutations with repetitions: When a word has repeated characters, the calculation becomes a little more involved. For example, the word "AABB" has 4! = 24 possible permutations if we consider the A's and B's as distinct. However, since the A's are indistinguishable from each other, as are the B's, we have to divide by the factorial of the count of each repeating character. Thus, the number of unique rearrangements of “AABB” is 4! / (2! 2!) = 24 / (2 2) = 6.

Here is a Python function that efficiently calculates the number of rearrangements:

import math
from collections import Counter

def count_rearrangements(word):
    char_counts = Counter(word)
    n = len(word)
    denominator = 1
    for count in char_counts.values():
        denominator = math.factorial(count)
    return math.factorial(n) // denominator

# Example usage:
print(count_rearrangements("CAT")) # Output: 6
print(count_rearrangements("AABB")) # Output: 6
print(count_rearrangements("MISSISSIPPI")) # Output: 34650

3. Explanation: The code utilizes the Counter object to count the occurrences of each character in the given word. Then it calculates the factorial of the length of the word. For repeating characters, the denominator is calculated by taking the factorial of the count of each repeated character and then multiplies them. The final result is obtained by dividing the factorial of the word's length by the accumulated factorial of counts.

This approach ensures accurate counting of rearrangements, handling both unique and repeated characters efficiently.

More questions