Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Determine the Order by PythonLearner
def checkio(words):
letters = set("".join(words))
indeces = {key: value for value, key in enumerate(letters)}
size = len(letters)
comparison_grid = [[0 if i == j else None for j in range(size)] for i in range(size)]
for word in words:
for i in range(len(word)-1):
for j in range(i+1, len(word)):
greater = indeces[word[i]]
lower = indeces[word[j]]
comparison_grid[greater][lower] = 1
comparison_grid[lower][greater] = -1
def fill_grid():
ambiguity_count = sum(sum(1 for comparison in row if comparison == None) for row in comparison_grid)
old_ambiguity_count = 0
while ambiguity_count and old_ambiguity_count != ambiguity_count:
old_ambiguity_count = ambiguity_count
rows = sorted(range(size), key=lambda i: sum(filter(None, comparison_grid[i])), reverse=True)
for row in rows:
for i in range(size):
if comparison_grid[row][i] == 1:
for j in range(size):
if comparison_grid[i][j] == 1:
comparison_grid[row][j] = 1
comparison_grid[j][row] = -1
ambiguity_count = sum(sum(1 for comparison in row if comparison == None) for row in comparison_grid)
fill_grid()
print(comparison_grid)
is_ambiguities = False
for row_letter in letters:
i = indeces[row_letter]
if any(comparison == None for comparison in comparison_grid[i]):
is_ambiguities = True
ambiguous = list(filter(lambda letter: comparison_grid[i][indeces[letter]] == None, letters))
ambiguous.append(row_letter)
ambiguous.sort()
index = ambiguous.index(row_letter)
if index < 0:
j = indeces[ambiguous[index-1]]
comparison_grid[j][i] = 1
comparison_grid[i][j] = -1
if index < len(ambiguous)-1:
j = indeces[ambiguous[index+1]]
comparison_grid[j][i] = -1
comparison_grid[i][j] = 1
if is_ambiguities:
fill_grid()
return "".join(sorted(letters, key=lambda letter: sum(comparison_grid[indeces[letter]]), reverse=True))
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(["acb", "bd", "zwa"]) == "zwacbd", \
"Just concatenate it"
assert checkio(["klm", "kadl", "lsm"]) == "kadlsm", \
"Paste in"
assert checkio(["a", "b", "c"]) == "abc", \
"Cant determine the order - use english alphabet"
assert checkio(["aazzss"]) == "azs", \
"Each symbol only once"
assert checkio(["dfg", "frt", "tyg"]) == "dfrtyg", \
"Concatenate and paste in"
Aug. 11, 2018