def answer(words): alphabet = [] rules = [] word_count = len(words) default_rule = ['1','1'] def get_word_rules(word1, word2): length = min(len(word1), len(word2)) print "comparing %s and %s" % (word1, word2) for x in range(length): if word1[x] != word2[x]: print "rule = %s, %s" % (word1[x], word2[x]) return [str(word1[x]), str(word2[x])] print "rule = %s, %s" % (1, 1) return default_rule # Find the rule that contains a letter that is never on the right # This is the first letter def find_first_letter(): length = len(rules) less_than_list = set() greater_than_list = set() for rule in rules: less_than_list.update(rule[0]) greater_than_list.update(rule[1]) #print less_than_list #print greater_than_list return (less_than_list - greater_than_list).pop(),(greater_than_list - less_than_list).pop() for index in range(word_count - 1): rule = get_word_rules(words[index], words[index+1]) if rule is not default_rule and rule not in rules: rules.append(rule) print "Rules list %s" % rules while len(rules) > 1: left_edge, right_edge = find_first_letter() print "left edge =%s" % left_edge print "Rules list %s" % rules old_rules = rules for rule in old_rules: # print rules print 'Testing rule %s' % rule if rule[0] == left_edge or rule[1] == right_edge: rules.remove(rule) alphabet_left.append( left_edge ) alphabet_right.insert(0, right_edge ) alphabet = alphabet_left + alphabet_right alphabet.append(rules[0][0]) if rules[0][1] not in alphabet: alphabet.append(rules[0][1]) return alphabet words = ["ba", "ab", "cb"] # words = ["z", "yx", "yz", "az", "ay", "baz", "bay"] words = ["z", "yx", "yz", "az","az", "ay", "baz", "bay"] words = ['c', 'cac', 'cb', 'bcc', 'ba'] # cab words = ['c', 'cac', 'cb', 'cz', 'bcc', 'ba'] # cabz print answer(words)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question