pythonreturnpermutationpredicateanagram

To test if a word is an anagram and output a boolean


I am a complete beginner in programming and I am trying to a write code to check if a word is an anagram whose output must be a boolean. When I run the code, the list of anagrams would include the initially entered word which is the first on the list, i.e. if it is an anagram or just the entered word if it isn't. It then returns the last return value even when it should be False.

def find_anagrams(words):

    from iterools import permutations
    import enchant
    d = enchant.Dict("en_GB")
    
    any_word = ("Enter a word /n")
    inp = any_word
    lettr = (x.lower() for x in inp)
    
    for y in  list(permutations(lettr)):
        z = "" join(y)
        if d.check(z):
            print(z)
            if z == inp: 
               return False
            else:
               return True 

print(find_anagrams("word"))   

Solution

  • Here is how you can check if a word is an anagram of another word in the enchant dictionary:

    from itertools import permutations
    import enchant
    d = enchant.Dict("en_GB")
    
    any_word = input("Enter a word \n")
    inp = any_word
    lettr = [x.lower() for x in inp]
    for y in permutations(lettr):
        z = "".join(y)
        if d.check(z) and z != inp:
            print(True)
            break
    else:
        print(False)
    

    Test run #1:

    Enter a word 
    bat
    

    Output:

    True
    

    Test run #2:

    Enter a word 
    good
    

    Output:

    False