Prefix matching in Python using pytrie module


In this article, we are going to learn about the pytrie module to prefix matching strings from a list of strings. Let's see an example to understand it clearly.

Input:
List: ['tutorialspoint', 'tutorials', 'tutorialspython', 'python']
Prefix: 'tutorials'

Output:
['tutorialspoint', 'tutorials', 'tutorialspython']

We can achieve it in different ways. In this tutorial, we are going to achieve it using the pytrie module.

From pytrie module, we will use the pytrie.StringTrie data structure. We can perform create, insert, search, and delete operations.

First, install the pytrie module with the following command.

pip install pytrie

Let's see steps to achieve the desired output.

  • Import the pytrie module.
  • Initialize the list, prefix.
  • Create a trie data structure using pytrie.StringTrie().
  • Iterate over the list and insert into the trie structure.
  • And print the values matching given prefix.

Example

# importing the module
import pytrie

# initializing the list and prefix
strings = ['tutorialspoint', 'tutorials', 'tutorialspython', 'python', 'learnpython']
prefix = 'tutorials'

# creating an trie data structure
trie = pytrie.StringTrie()

# iterating over the list and adding it to trie
for item in strings:
   trie[item] = item

# printing the matched strings
print(trie.values(prefix))

If you execute the above code, then you will get the following result.

Output

['tutorials', 'tutorialspoint', 'tutorialspython']

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on: 13-Nov-2020

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements