Learn how to enumerate all the strings that can be sorted and created.
Get rid of duplicate strings and sort
The steps are as follows.
- Permutation creates permutations and adds them to set variables.
- By adding it to the set variable, duplicate strings can be removed.
- Sorted the set variable and outputs the result.
from itertools import permutations s = "add" st = set() for it in permutations(s): st.add("".join(it)) print(sorted(st)) """ output ['add', 'dad', 'dda'] """
Reference: Output when not removing duplicate strings
Indicates the output when duplicate strings are not removed.
For comparison, the code for removing duplicate strings is commented out and added together.
from itertools import permutations s = "add" # st = set() l = [] for it in permutations(s): # st.add("".join(it)) l.append("".join(it)) # print(sorted(st)) print(sorted(l)) """ output ['add', 'add', 'dad', 'dad', 'dda', 'dda'] """
コメント