Skip to content Skip to sidebar Skip to footer

Python 3.3: Output Of Anagram Function

def anagram(word,check): for letter in word: if letter in check: check = check.replace(letter, '') else: return 0 return

Solution 1:

The way I understand your program, you want to continuously prompt the user for words until he presses Ctrl-D (which results in an EOF error and breaks the loop)? In that case, you should read the file only once, before the beginning of the loop, and construct a list or set of the words in it. Also, your try/except statement should only contain the call to input as this is the only place where this exception can occur in your function.

Now on to your main question - to count the number of results and print different statements accordingly, just use a list comprehension to get a list of all anagrams of the input. Then you can count the anagrams and join them together to form an output string.

deffind_anagrams():
    withopen("dictionary.txt", "r") as fileInput:
        words = set(word.strip() for word in fileInput)

    whileTrue:
        try:
            user_input = input("Word? ").strip()
        except:
            break#you probably don't care for the type of exception here

        anagrams = [word for word in words if anagram(word, user_input)]
        print_results(anagrams)

defprint_results(anagrams):
    iflen(anagrams) == 0:
        print("there are no anagrams")
    eliflen(anagrams) == 1:
        print("the only anagram is %s" % anagrams[0])
    else:
        print("there are %s anagrams: %s" % (len(anagrams), ', '.join(anagrams)))

The only thing missing from this code is cheking that the input word is not a part of the result list, but this can be moved to the anagram function. The function can also be simplified using the Counter class from the built-in collections module. This class is a dictionary-like object that can be constructed from an iterable and maps each object in the iterable to the number of its occurrences:

>>> Counter("hello") == {"h":1, "e":1, "l":2, "o": 1}
True

So we can rewrite the anagram function like this:

from collections import Counter

def anagram(word, check):
    returnnotword== check and Counter(word) == Counter(check)

Post a Comment for "Python 3.3: Output Of Anagram Function"