Методы поиска средней перестановки строки в Python

Чтобы найти среднюю перестановку строки в списке Python, вы можете использовать различные методы. Вот несколько примеров:

Метод 1. Использование библиотеки itertools

from itertools import permutations
def find_middle_permutation(string):
    # Generate all permutations of the string
    perms = permutations(string)

    # Sort the permutations lexicographically
    sorted_perms = sorted(perms)

    # Find the middle permutation
    middle_index = len(sorted_perms) // 2
    middle_permutation = ''.join(sorted_perms[middle_index])

    return middle_permutation
# Example usage
string = "abc"
middle_permutation = find_middle_permutation(string)
print(middle_permutation)

Метод 2: использование математически полученного индекса

import math
def find_middle_permutation(string):
    # Calculate the total number of permutations
    total_perms = math.factorial(len(string))

    # Sort the string characters
    sorted_string = sorted(string)

    # Calculate the index of the middle permutation
    middle_index = total_perms // 2 - 1

    # Generate the middle permutation
    middle_permutation = ''
    for i in range(len(string) - 1, -1, -1):
        index = middle_index // math.factorial(i)
        middle_permutation += sorted_string[index]
        sorted_string.pop(index)
        middle_index %= math.factorial(i)

    return middle_permutation
# Example usage
string = "abc"
middle_permutation = find_middle_permutation(string)
print(middle_permutation)

Метод 3. Использование рекурсии

def find_middle_permutation(string):
    if len(string) <= 1:
        return string

    middle_index = (len(string) - 1) // 2
    middle_char = string[middle_index]

    left_chars = [ch for ch in string if ch < middle_char]
    middle_chars = [ch for ch in string if ch == middle_char]
    right_chars = [ch for ch in string if ch > middle_char]

    sorted_string = ''.join(left_chars + middle_chars + right_chars)

    return find_middle_permutation(sorted_string)
# Example usage
string = "abc"
middle_permutation = find_middle_permutation(string)
print(middle_permutation)