• 1
    Entrée et sortie
    • Tâches
  • 2
    Conditions
    • Tâches
  • 3
    Boucle for
    • Tâches
  • 4
    Chaînes
    • Tâches
  • 5
    Boucle while
    • Tâches
  • 6
    Listes
    • Tâches
  • 7
    Tableaux 2D
    • Tâches
  • 8
    Dictionnaires
    • Tâches
  • 9
    Ensembles
    • Tâches
  • 10
    Fonctions et récursion
    • Tâches
  • к

Leçon 4. Lines

Difficulté :

Exercice«Symbole moyen»

💻 Python

Imagine that you are a linguist-archaeologist, and you found an ancient artifact with a set of characters. You suggest that this is an anagram — a puzzle in which you need to rearrange the letters of a given word so that another word is obtained. To hack the cipher, you need to compile a full dictionary of all possible combinations of characters that could be encrypted.

Your task — write a program that accepts one word (set of characters) as input and displays all unique combinations (permutations) of these characters. For the convenience of analysis and comparison with ancient texts, all the resulting combinations should be sorted in alphabetical order.

For example, if the word on the artifact is «cat», your program should generate and display the words «cat», «cta», «act», «atc», «tac», «tca».

 

Format d entrée

Le mot pour générer des permutations (chaîne de caractères). Il peut s'agir d'une seule ligne sans espaces contenant des lettres ou des chiffres.

Format de sortie

Tous les réarrangements uniques des symboles du mot d'entrée triés par ordre alphabétique. Chaque permutation est affichée sur une nouvelle ligne (chaîne).

Exemple

Entrée

Maison

Sortie

DMO
Maison
MDO
Mod
ODM
OMD

Indice

There will be no clue here, decide for yourself!

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Solution du développeur
# Для решения этой сложной задачи нам понадобится специальный инструмент
# для создания перестановок. Мы импортируем его из стандартной библиотеки itertools.
from itertools import permutations

# Считываем слово, которое ввел пользователь
word = input()

# Генерируем все возможные перестановки символов в слове.
# Функция permutations возвращает объекты-кортежи, например, для слова "ab" это будут ('a', 'b') и ('b', 'a').
all_perms_tuples = permutations(word)

# Чтобы избавиться от дубликатов (например, для слова "aab"), мы используем множество (set).
# В цикле мы преобразуем каждый кортеж обратно в строку и добавляем в множество.
# Множество автоматически сохранит только уникальные строки.
unique_perms_set = set()
for p in all_perms_tuples:
    # Метод .join() склеивает символы из кортежа в одну строку.
    # Например, ('д', 'о', 'м') превращается в "дом".
    unique_perms_set.add("".join(p))

# Для сортировки нам нужен список, поэтому преобразуем множество в список.
sorted_perms = sorted(list(unique_perms_set))

# Теперь, когда у нас есть отсортированный список уникальных перестановок,
# мы выводим каждый элемент этого списка на новой строке.
for perm in sorted_perms:
    print(perm)

🎉 Félicitations ! 🎉

Tu as brillamment résolu la tâche ! C était difficile, mais tu as trouvé la bonne solution. Tu es encore plus proche de maîtriser la programmation ! Continue ainsi.

AD

Publicité

red-snake blue-snake green-snake

Exécution de votre code...

Assistant IA

Bonjour ! Je suis ton assistant de programmation. Pose moi toutes tes questions sur Python — je peux t expliquer les fonctions, les méthodes et t aider avec la tâche en cours !