Python3建立乙個trie的兩種方法

2022-06-20 16:15:11 字數 2557 閱讀 6083

trie即字首樹字典樹,利用字串公共字首降低搜尋時間。速度為o(k),k為輸入的字串長度。

1.採用defaultdict建立trie

from collections import defaultdict

from functools import reduce

trienode = lambda: defaultdict(trienode)

class trie:

def __init__(self):

self.trie = trienode()

def insert(self, word):

reduce(dict.__getitem__, word, self.trie)['end'] = true

def search(self, word):

return reduce(lambda d,k: d[k] if k in d else trienode(), word, self.trie).get('end', false)

def startswith(self, word):

return bool(reduce(lambda d,k: d[k] if k in d else trienode(), word, self.trie).keys())

2.採用dictionary結構

#定義trie結構體

class trienode(object):

def __init__(self):

"""initialize your data structure here.

"""self.data = {}

self.is_word = false

class trie(object):

def __init__(self):

self.root = trienode()

def insert(self, word):

"""inserts a word into the trie.

:type word: str

:rtype: void

"""node = self.root

for letter in word:

child = node.data.get(letter)

if not child:

node.data[letter] = trienode()

node = node.data[letter]

node.is_word = true

def search(self, word):

"""returns if the word is in the trie.

:type word: str

:rtype: bool

"""node = self.root

for letter in word:

node = node.data.get(letter)

if not node:

return false

return node.is_word # 判斷單詞是否是完整的存在在trie樹中

def starts_with(self, prefix):

"""returns if there is any word in the trie

that starts with the given prefix.

:type prefix: str

:rtype: bool

"""node = self.root

for letter in prefix:

node = node.data.get(letter)

if not node:

return false

return true

def get_start(self, prefix):

"""returns words started with prefix

:param prefix:

:return: words (list)

"""def _get_key(pre, pre_node):

words_list =

if pre_node.is_word:

for x in pre_node.data.keys():

words_list.extend(_get_key(pre + str(x), pre_node.data.get(x)))

return words_list

words =

if not self.starts_with(prefix):

return words

if self.search(prefix):

return words

node = self.root

for letter in prefix:

node = node.data.get(letter)

return _get_key(prefix, node)

Trie的乙個實現

trie.h 檔案 ifndef trie h define trie h include include include include include using namespace std inline int sub size int level struct search tree cha...

python3執行緒加鎖的乙個例子

再這個例子中,執行緒加上鎖之後有並行變成了實際上的序列 root linux1 python tidb cat mypy02.py usr bin env python3 import pymysql,sys,os import thread,time def counter myid,count ...

Python3多個Excel寫入同乙個

coding utf 8 import time import requests import re import os from bs4 import beautifulsoup from requests.exceptions import connectionerror,readtimeout...