itertools.permutations() | HackerRank
itertools.permutations() | HackerRank
Find all permutations of a given size in a given string.
www.hackerrank.com
Goal
You are given a string S.
Your task is to print all poissible permutations of size K of the string in lexicographic sorted order.
Solution
You need to use itertools.permutations(iterable[, r]) method to solve this task.
The itertools module in Python provides a number of powerful functions for working with iterable objects.
One of these functions is permutations(), which generates all possible permutations of an iterable object.
The input() function is used to read a line of input from standard input,
and the split() method is used to split the input line into a list of strings.
The first element in the list is the string that we want to generate permutations for,
and the second element is the length of the permutations that we want to generate.
The permutations() function is called with two arguments:
the first is the string that we want to generate permutations for, and the second is the length of the permutations.
The list() function is called to convert the result to a list. The list of permutations is stored in the perm variable.
The perm list is iterated over using a for loop, and a new string is created for each permutation.
The join() method is used to concatenate the elements of the permutation into a string,
and the resulting string is appended to the results list.
Once all the permutations have been generated,
the sorted() function is called to sort the results list in lexicographic order.
The join() method is used to concatenate the sorted strings together with a newline character,
and the resulting string is printed to standard output.
# itertools.permutations()
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import permutations
com = input().split()
perm = list(permutations(com[0], int(com[1])))
results = []
for element_set in perm:
tmp = ""
for element in element_set:
tmp += element
results.append(tmp)
print('\n'.join(sorted(results)))
'software Engineering > (Python)HackerRank' 카테고리의 다른 글
[Python] HackerRank - DefaultDict Tutorial (0) | 2023.02.25 |
---|---|
[Python] HackerRank - Introduction to Sets (0) | 2023.02.24 |
[Python] HackerRank - collections.Counter() (0) | 2023.02.22 |
[Python] HackerRank - itertools.product() (0) | 2023.02.21 |
[Python] HackerRank - Capitalize! (0) | 2023.02.19 |