Skip to content

Instantly share code, notes, and snippets.

@nrubin29
Created May 26, 2016 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nrubin29/eaa111430cc65151311bf1da1277061f to your computer and use it in GitHub Desktop.
Save nrubin29/eaa111430cc65151311bf1da1277061f to your computer and use it in GitHub Desktop.
minglish_lesson solution
def answer(words):
# first, we need to generate the graph
vertices = []
letters = list(set([val for sublist in [list(word) for word in words] for val in sublist]))
for word in words:
for letter in list(word):
letters.append(letter)
for i in range(len(words) - 1):
word_a = words[i]
word_b = words[i + 1]
for j in range(min(len(word_a), len(word_b))):
if word_a[j] != word_b[j]:
letter_a = word_a[j]
letter_b = word_b[j]
vertices.append((letter_a, letter_b))
break
dfs = []
marked = []
pool = letters # the pool of letters. needed because I use pop()
while len(pool) > 0:
node = pool.pop()
visit(node, vertices, dfs, marked)
return ''.join(dfs)
def visit(node, vertices, dfs, marked):
if node not in marked:
marked.append(node)
for vertex in vertices:
if vertex[0] == node:
visit(vertex[1], vertices, dfs, marked)
dfs.insert(0, node)
print(answer(["z", "yx", "yz"])) # xzy
print(answer(["ba", "ab", "cb"])) # bac
print(answer(["y", "z", "xy"])) # yzx
print(answer(['c', 'cac', 'cb', 'bcc', 'ba'])) # cab
print(answer(['abc', 'bad', 'dba', 'cab'])) # a > b; b > d; d > c
print answer(['abc', 'abd', 'bda', 'cda']) # c > d; a > b; b > c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment