Reputation: 146
I am writing a code in which I want to search a datafile with words - a wordbook. Just for fun! The idea is to define some letters, and the program will then find words containing the exact input. I have already written the code and succeded, but it really needs some adjustments too give the right output.
This is the code block:
def findword():
letters = set(str(raw_input("Type letters: ")))
for item in wordlist: # already defined list containing the words
if letters >= set(item):
if len(item) <= len(letters):
print item
I am using set to compare the letters with the list of words. The problem is that the output can be words containing two of the same letter even though input may only contain one of that specific letter. So how can I make sure the output will be the exact input letters but not arranged the same way? I'd appreciate if you would take the time to help me out with this! Thanks!
Alex
Upvotes: 0
Views: 219
Reputation: 7631
If you just want to change the arrangement of the output then generate two random number between 0 and len(outputStr-1)/2 and between len(outputStr-1)/2+1 and len(outputStr)-1 and swap them.
Upvotes: 0
Reputation: 95348
I interpret your question in the way that if the input is, e.g., abc
, you want to match cba
or bca
, but not abcd
or abcc
. So basically you want to find anagrams.
You can use a dictionary to keep track of the number of occurrences of each letter:
from collections import defaultdict
def make_letter_dict(word):
letters = defaultdict(int)
for c in word:
letters[c] += 1
letters = make_letter_dict(raw_input("Letters: "))
words = (w for w in wordlist if make_letter_dict(w) == letters)
Upvotes: 1