หาสตริงที่ขึ้นต้นด้วย Prefix ที่กำหนดจากลิสต์สตริง
ตัวอย่าง: ลิสต์ ['tutorialspoint', 'tutorials', 'tutorialspython', 'python'], Prefix 'tutorials' → ผลลัพธ์ ['tutorialspoint', 'tutorials', 'tutorialspython']
ขั้นตอนใช้ pytrie
- ติดตั้ง:
pip install pytrie - Import และสร้าง
pytrie.StringTrie() - Insert สตริงทั้งหมดเข้า Trie
- ใช้
trie.values(prefix)ดึงค่าที่ตรง Prefix
ตัวอย่างโค้ด
import pytrie
strings = ['tutorialspoint', 'tutorials', 'tutorialspython', 'python', 'learnpython']
prefix = 'tutorials'
trie = pytrie.StringTrie()
for item in strings:
trie[item] = item
print(trie.values(prefix))
# ['tutorials', 'tutorialspoint', 'tutorialspython']
สรุป
Trie ใช้ค้นหา Prefix ได้เร็ว O(m) โดย m = ความยาว prefix เหมาะสำหรับ autocomplete