簡體   English   中英

在 Trie 字典中搜索前綴

[英]Prefix search in a Trie dictionary

我有一個示例字典

    {  
   'A':{  
      'P':{  
         'P':{  
            'L':{  
               'I':{  
                  'E':{  
                     'S':{  
                        '*':True
                     }
                  }
               },
               'E':{  
                  'S':{  
                     '*':True
                  },
                  '*':True
               }
            }
         },
         'E':{  
            '*':True
         }
      }
   }
}

這里{*:True}表示單詞的結尾。 我需要找到我可以從字典中以前綴開頭的所有可能的單詞。 例如,我可以從上面帶有各種前綴的字典中生成的單詞如下。

  1. 'AP' - > “蘋果”、“蘋果”、“猿”、“蘋果”

  2. 'APP' -> "APPLE", "APPLES", "APPLIES"

  3. “蘋果”->“蘋果”,“蘋果”

我基本上是在嘗試使用字典實現Trie數據結構並執行前綴搜索。 我想我應該實現一些遞歸算法來找到所有可能的結果。 我無法弄清楚如何實現它。

我很好奇並想出了這個遞歸變體:

tree = {
    "A": {
        "P": {
            "P": {
                "L": {
                    "I": {"E": {"S": {"*": True}}},
                    "E": {"S": {"*": True}, "*": True},
                }
            },
            "E": {"*": True},
        }
    }
}


def descend(node, prefix=""):
    if prefix and prefix[-1] == "*":
        print(prefix[:-1])
        return
    for letter, node in node.items():
        descend(node, prefix + letter)


descend(tree)

它打印:

APPLIES
APPLES
APPLE
APE

您可以將遞歸與生成器一起使用:

data = {'A': {'P': {'P': {'L': {'I': {'E': {'S': {'*': True}}}, 'E': {'S': {'*': True}, '*': True}}}, 'E': {'*': True}}}}
def combos(d, c = []):
  for a, b in d.items():
    yield from [''.join(c)] if isinstance(b, bool) else combos(b, c+[a])


print(list(combos(data['A']['P'], ['A', 'P'])))

輸出:

['APPLIES', 'APPLES', 'APPLE', 'APE']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM