• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Занятие 4. Lines

Difficulty level:

Task«Average symbol»

imagine that you are & mdash; Linguist-archaeologist, and you found an ancient artifact with a set of characters. You suggest that this is anam & mdash; 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.

rn

your task & mdash; Write a program that accepts one word (set of characters) to the 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.

rn

for example, if a word is placed on an artifact on an artifact & laquo; cat & raquo;, your program should generate and display the words & laquo; cat & raquo;, & laquo; who & raquo;, & laquo; Oct & raquo ;, & laquo; & laquo; MSW & raquo ;, & laquo; current & raquo;.

rn

& nbsp;

Input format

The word for generating permutations (string). It can be one line without spaces containing letters or numbers.

Output format

All unique rearrangements of the symbols of the input word sorted in alphabetical order. Each permutation is displayed on a new line (string).

Example

Input

House

Output

DMO
House
MDO
Mod
ODM
OMD

Hint

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
Developer’s solution
# Для решения этой сложной задачи нам понадобится специальный инструмент
# для создания перестановок. Мы импортируем его из стандартной библиотеки 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)

🎉 Congratulations! 🎉

You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

AD

Advertisement

red-snake blue-snake green-snake

Running your code...

Помощник ИИ

Привет! Я твой помощник по программированию. Задавай любые вопросы по Python, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!