Created
September 23, 2019 08:01
-
-
Save tonymontaro/a3d0bbb45d907450d719697a3dcc7dbd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Awa's problem: | |
| # "Assume we have a list of words from the English dictionary, like: | |
| # EnglishWords: ['water','big','apple','watch','banana','york','amsterdam','orange','macintosh','bottle','book']; | |
| # And another long list of string to process, write a function to identify ""compound words"" and return them: | |
| # input: ['paris','applewatch','ipod','amsterdam','bigbook','orange','waterbottle'] | |
| # output: ['applewatch','bigbook','waterbottle'] | |
| class SuffixTrie: | |
| def __init__(self): | |
| self.root = {} | |
| self.endSymbol = "*" | |
| def addWord(self, string): | |
| node = self.root | |
| for char in string: | |
| if char not in node: | |
| node[char] = {} | |
| node = node[char] | |
| node['*'] = True | |
| def isCompound(self, word): | |
| node = self.root | |
| endChars = [] | |
| for char in word: | |
| if char not in node: | |
| return False | |
| if '*' in node[char]: | |
| endChars.append(char) | |
| node = self.root | |
| continue | |
| node = node[char] | |
| return len(endChars) >= 2 and word[-1] == endChars[-1] | |
| def __repr__(self): | |
| return str(self.root) | |
| # O(N + M) | |
| def main(englishWords, words): | |
| dictionary = SuffixTrie() | |
| for word in englishWords: | |
| dictionary.addWord(word) | |
| return [word for word in words if dictionary.isCompound(word)] | |
| englishWords = ['water','big','apple','watch','banana','york','amsterdam','orange','macintosh','bottle','book'] | |
| words = ['paris','applewatch','ipod','amsterdam','bigbook','orange','waterbottle', 'applewatchipod'] | |
| main(englishWords, words) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment