Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Prefix Matching ใน Python ด้วยโมดูล pytrie

หาสตริงที่ขึ้นต้นด้วย Prefix ที่กำหนดจากลิสต์สตริง

ตัวอย่าง: ลิสต์ ['tutorialspoint', 'tutorials', 'tutorialspython', 'python'], Prefix 'tutorials' → ผลลัพธ์ ['tutorialspoint', 'tutorials', 'tutorialspython']

ขั้นตอนใช้ pytrie

  1. ติดตั้ง: pip install pytrie
  2. Import และสร้าง pytrie.StringTrie()
  3. Insert สตริงทั้งหมดเข้า Trie
  4. ใช้ 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