Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
There must be a better way solution in Clear category for Determine the Order by jakubbortlik
from itertools import combinations
def group(string: str) -> str:
"""Remove duplicate characters and keep order."""
return "".join(dict.fromkeys(string))
def find_next(chars: set, data: list, result: list) -> set:
"""Find the next character for the result list.
Args:
chars: Characters whose order still needs to be found
out.
data: Original input strings.
result: Current list of result characters.
Returns:
Set of chars that are not preceded by anything else
than the chars already in the result.
"""
tmp_chars = set(chars)
for word in data:
for char in set(word) & tmp_chars:
index = word.find(char)
if any(c not in result for c in (word[:index])):
tmp_chars.remove(char)
return tmp_chars
def can_determine_order(data):
return any(set(x) & set(y) for x, y in combinations(data, 2))
def checkio(data):
"""Return sorted string of all unique characters in `data`.
The order is determined by the order in the `data` strings or by
alphabetical order.
"""
result = []
chars = set("".join(data))
n_chars = len(chars)
if not can_determine_order(data):
return "".join(sorted(group(s) for s in data))
while len(result) < n_chars:
next_char = find_next(chars, data, result)
chars -= next_char
result.extend(sorted(next_char))
return "".join(result)
Dec. 15, 2022
Comments: