Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution in Clear category for All Permutations by freeman_lex
from collections.abc import Iterable
def string_permutations(s: str) -> Iterable[str]:
if len(s) < 2: return [s]
all = []
for i, char in enumerate(s):
remaining_chars = s[:i] + s[i + 1:]
for perm in string_permutations(remaining_chars):
all.append(char + perm)
return sorted(all)
print("Example:")
print(list(string_permutations("ab")))
# These "asserts" are used for self-checking
assert list(string_permutations("ab")) == ["ab", "ba"]
assert list(string_permutations("abc")) == ["abc", "acb", "bac", "bca", "cab", "cba"]
assert list(string_permutations("a")) == ["a"]
assert list(string_permutations("abcd")) == [
"abcd",
"abdc",
"acbd",
"acdb",
"adbc",
"adcb",
"bacd",
"badc",
"bcad",
"bcda",
"bdac",
"bdca",
"cabd",
"cadb",
"cbad",
"cbda",
"cdab",
"cdba",
"dabc",
"dacb",
"dbac",
"dbca",
"dcab",
"dcba",
]
print("The mission is done! Click 'Check Solution' to earn rewards!")
Sept. 11, 2023
Comments: