Malaka
Malaka

Reputation: 326

Search a list of string with a given substring in python

I'm developing a dictionary kind of application using python. In my code, there is a list which consists of sorted set of strings. when a user give some text, I want to get all the string starting with the given string. In other words, I just want to suggest words while user is typing.

Example : If user typed the word "sub", I want to take all the string from the list starting with the substring "sub".

Can anyone give me an algorithm to do this? Thanks all.

Upvotes: 1

Views: 351

Answers (2)

kasavbere
kasavbere

Reputation: 6003

What you need is a trie data structure, which is perfect for what you seek. Your code needs to handle heavy read/retrieval. Look up trie. if you need implementation let me know.

Upvotes: 0

Colin
Colin

Reputation: 10820

Depending on the size of the list, you could just iterate through it and use the startswith() string function to get the result. If that's too slow, a common way is to use a prefix tree.

Upvotes: 1

Related Questions