Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Anagrams recursion [closed]

Tags:

python

anagram

I have this code:

mylist = open('sortedwords.txt')
txt = mylist.read()
mylist = txt.split()
stuff = input('Type a word here: ')

def removeletters (word, Analysis):
    for char in range (len(Analysis)):
        if Analysis [char] in word:
             word = word.replace(Analysis[char],"",1)
    return word

def anagramSubset(word, textList):
    newWord = word
    for char in range(len(textList)):
        if textList[char] not in newWord: 
            return False
        else:
           newWord = newWord.replace(textList[char],"",1)
    return True

def anagram(word, textList):
    savedWords =[]
    for checkword in textList:  
        if len(word) == len(checkword) and anagramSubset(word, checkword):
            savedWords.append(checkword)
            print(checkword)
                    
anagram(stuff, mylist)

It is supposed to take an input word, remove letters from the input word, then make a subset of words and save that to an array to print off of.

The problem is that the code will save every word that can be created from the input. E.g. an input of spot results in top, tops, stop, pots, pot, etc. The result should only have tops, pots, and stop.

What is wrong with the code, and how do I fix it?

like image 398
user3040579 Avatar asked Feb 16 '26 05:02

user3040579


1 Answers

I looked at the code and am wondering what the recursion is adding? The first pass does all of the computational work and then the recursion adds some extra stack frames and alters how output is printed. Am I making the wrong assumption that textList is a list of valid words split from a single line in a file?

When I run this locally with a particular word list, this gets the same effect (in the sense that it finds words whose letters are a subset) with less thrashing:

def anagram(word, textList):
    savedWords = []
    for checkword in textList:
        if anagramSubset(word, checkword):
            savedWords.append(checkword)
    print(savedWords)

If the problem eventually becomes that you're getting words that have too few letters, you could fix your problem by checking that a word is the length of the original word before you add it with:

if len(original_word) == len(checkword):
    savedWords.append(checkword)
like image 117
Tim Wilder Avatar answered Feb 18 '26 19:02

Tim Wilder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!