solo fisher
solo fisher

Reputation: 65

Create a dict whose value is the set of all possible anagrams for a given word

So what im trying to do is create a dict whose:

When i run my program i get Ex. word : {('w', 'o', 'r', 'd')} not word : dorw, wrdo, rowd. Text file just contains a lot of words one on each line.

Code:

def main():
    wordList = readMatrix()
    print(lengthWord())

def readMatrix():
    wordList = []
    strFile = open("words.txt", "r")
    lines = strFile.readlines()
    for line in lines:
        word = sorted(line.rstrip().lower())
        wordList.append(tuple(word))
    return tuple(wordList)

def lengthWord():
    lenWord = 4
    sortDict = {}
    wordList = readMatrix()
    for word in wordList:
        if len(word) == lenWord:
            sortWord = ''.join(sorted(word))
            if sortWord not in sortDict:
                sortDict[sortWord] = set()
            sortDict[sortWord].add(word)
    return sortDict


main()

Upvotes: 0

Views: 126

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123410

You are creating tuples of each word in the file:

for line in lines:
    word = sorted(line.rstrip().lower())
    wordList.append(tuple(word))

This will sort all your anagrams, creating duplicate sorted character tuples.

If you wanted to track all possible words, you should not produce tuples here. Just read the words:

for line in lines:
    word = line.rstrip().lower()
    wordList.append(word)

and process those words with your lengthWord() function; this function does need to take the wordList value as an argument:

def lengthWord(wordList):
    # ...

and you need to pass that in from main():

def main():
    wordList = readMatrix()
    print(lengthWord(wordList))

Upvotes: 2

Related Questions