List all words in a dictionary that start with <user input>


How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?

User: "abd"
Program:abdicate, abdomen, abduct...


Edit: I'm using python, but I assume that this is a fairly language-independent problem.


Most Pythonic solution

# set your list of words, whatever the source
words_list = ('cat', 'dog', 'banana')
# get the word from the user inpuit
user_word = raw_input("Enter a word:\n")
# create an generator, so your output is flexible and store almost nothing in memory
word_generator = (word for word in words_list if word.startswith(user_word))

# now you in, you can make anything you want with it 
# here we just list it :

for word in word_generator :
    print word

Remember generators can be only used once, so turn it to a list (using list(word_generator)) or use the itertools.tee function if you expect using it more than once.

Best way to do it :

Store it into a database and use SQL to look for the word you need. If there is a lot of words in your dictionary, it will be much faster and efficient.

Python got thousand of DB API to help you do the job ;-)

By : e-satis

A linear scan is slow, but a prefix tree is probably overkill. Keeping the words sorted and using a binary search is a fast and simple compromise.

import bisect
words = sorted(map(str.strip, open('/usr/share/dict/words')))
def lookup(prefix):
    return words[bisect.bisect_left(words, prefix):bisect.bisect_right(words, prefix+'~')]

>>> lookup('abdicat')
['abdicate', 'abdication', 'abdicative', 'abdicator']
By : Coady

Don't use a bazooka to kill a fly. Use something simple just like SQLite. There are all the tools you need for every modern languages and you can just do :

"SELECT word FROM dict WHERE word LIKE "user_entry%"

It's lightning fast and a baby could do it. What's more it's portable, persistent and so easy to maintain.

Python tuto :

By : e-satis

This video can help you solving your question :)
By: admin