ok, i have this code:
colors = ["Red" , "Green" , "Blue" , "Pink" , "Purple" , "Cyan"]
search = str(raw_input())
found = "not"
if search in colors:
print "Found!"
else:
print "not Found"
so far, it can find one item in a list only if you type the string in the terminal exactly as it is in the list, that is the problem.
i need to be able to type one or two characters in the terminal and have it so that it lists the strings inside the list that matches the search (for example: if i were to type "P" the terminal, it would list "Pink" and "Purple" because they match my search so far, but not exactly)
I may be overlooking something but, is there a way i can search a list this way without having to have over 200 lines of code (200+ lines because what i need to implement this to has over 150 strings in the list) just for searching for the string?
The simplest way, using a list comprehension:
matches = [color for color in colors if color.startswith(search)]
If you have a large list this might not perform so well.
What you need is a proper data structure. From your requirement description, I think trie is just the one.
You build a trie with a list of colors and then search the trie with user inputs (prefix is allowed). You can find diverse implementations on github or implement it yourself. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With