【问题标题】:How to change this prefix trie to return all words that contain similar prefixes如何更改此前缀尝试返回包含相似前缀的所有单词
【发布时间】:2016-08-25 06:52:55
【问题描述】:

您好,这是我的前缀 trie 代码的一部分,我试图让它返回的不仅仅是前缀,底部还有更多解释:

class TrieNode:
    def __init__(self):
        self.isString = False
        self.children = {}


def insertString(word, root):
    currentNode = root
    for char in word:
        if char not in currentNode.children:
            currentNode.children[char] = TrieNode()
        currentNode = currentNode.children[char]
    currentNode.isString = True


def findStrings(prefix, node, results):
    if node.isString:
        results.append(prefix)
    for char in node.children:
        findStrings(prefix + char, node.children[char], results)


def longestPrefix(word, root):
    currentNode = root
    currentPrefix = ''
    for char in word:
        if char not in currentNode.children:
            break
        else:
            currentNode = currentNode.children[char]
            currentPrefix += char
    strings = []
    findStrings(currentPrefix, currentNode, strings)
    return strings
    pass
    # Discussion: Is it dangerous to assume that findStrings actually found a string?
    # Hint: There is an edge case that will break this


wordList = ['aydt', 'coombs', 'schuhmacher', 'claypoole', 'exhume', 'forehands', 'carin', 'plaits', 'alfonsin',
            'hometowns', 'pedestals', 'emad', 'hourly', 'purchaser', 'spogli', 'combativeness', 'henningsen', 'luedke',
            'duchin', 'koglin', 'teason', 'bumpings', 'substantially', 'lamendola', 'cecola', 'henze', 'tutti', 'dills',
            'satirical', 'jetted', 'intertwine', 'predict', 'breezes', 'cyclist', 'ancillary', 'schaumburg', 'viewer',
            "bay's", 'emissions', 'kincheloe', 'trees', 'vipperman', 'exhale', 'ornamental', 'repeated', 'pedestal',
            'pedesta', 'pedest']

root = TrieNode()

for word in wordList:
    insertString(word, root)

allWords = []
findStrings('', root, allWords)
print(allWords)

inputWord = 'co'
print(longestPrefix(inputWord, root))

inputWord = 'pedestals'
print(longestPrefix(inputWord, root))

我试图了解如何让print(longestPrefix('pedestals', root)) 返回“基座”、“基座”、“基座”、“基座”,而不仅仅是基座。我的代码中缺少什么?

【问题讨论】:

    标签: python prefix trie


    【解决方案1】:

    我试图了解如何获得 print(longestPrefix('pedestals', root)) 返回 'pedestals','pedestal','pedesta', 'pedest' 而不是 只是基座。

    由于 pedestals 不是前缀,考虑到代码的逻辑,这没有任何意义——我希望您想知道为什么 print(longestPrefix('pedest', root)) 没有返回这四个结果.我在下面重新编写了您的代码,将您的所有函数都转换为方法,因为每个函数都将您定义的对象作为参数:

    class TrieNode:
        def __init__(self):
            self.isString = False
            self.children = {}
    
        def insertString(self, word):
            for char in word:
                if char not in self.children:
                    self.children[char] = TrieNode()
                self = self.children[char]
            self.isString = True
    
        def findStrings(self, prefix):
            results = []
            if self.isString:
                results.append(prefix)
    
            for char in self.children:
                results.extend((self.children[char]).findStrings(prefix + char))
    
            return results
    
        def longestPrefix(self, word):
            currentPrefix = ''
    
            for char in word:
                if char not in self.children:
                    break
                else:
                    self = self.children[char]
                    currentPrefix += char
    
            return self.findStrings(currentPrefix)
    
    wordList = [
        'aydt', 'coombs', 'schuhmacher', 'claypoole', 'exhume', 'forehands', 'carin', 'plaits', 'alfonsin',
        'hometowns', 'pedestals', 'emad', 'hourly', 'purchaser', 'spogli', 'combativeness', 'henningsen', 'luedke',
        'duchin', 'koglin', 'teason', 'bumpings', 'substantially', 'lamendola', 'cecola', 'henze', 'tutti', 'dills',
        'satirical', 'jetted', 'intertwine', 'predict', 'breezes', 'cyclist', 'ancillary', 'schaumburg', 'viewer',
        "bay's", 'emissions', 'kincheloe', 'trees', 'vipperman', 'exhale', 'ornamental', 'repeated', 'pedestal',
        'pedesta', 'pedest'
    ]
    
    root = TrieNode()
    
    for word in wordList:
        root.insertString(word)
    
    allWords = root.findStrings('')
    print(allWords)
    
    inputWord = 'co'
    print(root.longestPrefix(inputWord))
    
    inputWord = 'pedest'
    print(root.longestPrefix(inputWord))
    

    最后两个打印语句输出:

    ['coombs', 'combativeness']
    ['pedest', 'pedesta', 'pedestal', 'pedestals']
    

    【讨论】:

      【解决方案2】:
      wordList = ['aydt', 'coombs', 'schuhmacher', 'claypoole', 'exhume', 'forehands', 'carin', 'plaits', 'alfonsin',
                  'hometowns', 'pedestals', 'emad', 'hourly', 'purchaser', 'spogli', 'combativeness', 'henningsen', 'luedke',
                  'duchin', 'koglin', 'teason', 'bumpings', 'substantially', 'lamendola', 'cecola', 'henze', 'tutti', 'dills',
                  'satirical', 'jetted', 'intertwine', 'predict', 'breezes', 'cyclist', 'ancillary', 'schaumburg', 'viewer',
                  "bay's", 'emissions', 'kincheloe', 'trees', 'vipperman', 'exhale', 'ornamental', 'repeated', 'pedestal',
                  'pedesta', 'pedest']
      
      def findsubstring(fullstring):
          for word in wordList:
              if word in fullstring:
                  print (word)
      
      findsubstring("pedestals")
      

      输出:

      pedestals
      pedestal
      pedesta
      pedest
      

      【讨论】:

      • in 似乎不正确 - 使用startswith 可能更好。但这并没有使用 OP 的 trie 结构,所以它只是解决问题的一种替代方案。
      猜你喜欢
      • 2022-08-21
      • 2020-08-18
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 2013-04-26
      • 2021-06-13
      相关资源
      最近更新 更多