Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Swapping letters towards the left solution in Clear category for Determine the Order by Splitter
def checkio(data):
# Construct an initial alphabet.
alph = sorted(set(''.join(data)))
# Will be used for checking the input order
# and restoring the default latin order.
# Will store info about which letters are to the left
# and which ones are to the right from a letter.
letters_adjacency = {ch: {'left': set(), 'right': set()} for ch in alph}
for word in data:
for ch in word:
parts = word.partition(ch)
letters_adjacency[ch]['left'] |= set(parts[0])
letters_adjacency[ch]['right'] |= set(parts[-1])
order_alphabet(data, alph)
# Sometimes ordering should be carried out many times.
while not check_order(alph, letters_adjacency):
order_alphabet(data, alph)
# Find adjacent letters that were not ordered by words in data.
all_letters = set(alph)
unordered_pairs = []
for k, v in letters_adjacency.items():
neighbors = v['left'] | v['right']
unordered_letters = all_letters - neighbors - set(k)
for l in unordered_letters:
if abs(alph.index(k) - alph.index(l)) == 1:
unordered_pairs += [''.join(sorted(k + l))]
restored_order_pairs = list(dict.fromkeys(unordered_pairs))
# Restore default order that could become broken after that letter moving.
order_alphabet(restored_order_pairs, alph)
return ''.join(alph)
def order_alphabet(data, alph):
for word in filter(lambda x: len(x) > 1, data):
for w_i in range(len(word) - 1):
# It will be recomputing further.
chs_on_the_right = [False]
alph_i = alph.index(word[w_i])
while chs_on_the_right and not all(chs_on_the_right):
if alph_i == 0:
break
# List of statuses about whether a symbol, placed to the right
# from the current symbol at `w_i`, is placed to the right
# in the alph too.
chs_on_the_right = [alph_i < alph.index(word[r_i])
for r_i in range(w_i + 1, len(word))
if word[r_i] != alph[alph_i]]
if chs_on_the_right and not all(chs_on_the_right):
alph[alph_i], alph[alph_i - 1] = alph[alph_i - 1], alph[alph_i]
alph_i = alph.index(word[w_i])
def check_order(alph, letters_adjacency):
for k, v in letters_adjacency.items():
letter_i = alph.index(k)
for left_ch in letters_adjacency[k]['left']:
if alph.index(left_ch) > letter_i:
return False
return 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"
March 4, 2020
Comments: