I'm trying to arrange a list of anagrams from shortest to longest with the help of a text document. I'm not sure how to do this. I've tried arranging the anagrams but I can't seem to get it to work.

# function that sorts letters in a string in ascending order 
def signature ( s ):
    t = sorted( s )
    return ''.join(t)

# function that builds a dictionary whose keys are the signatures of the
# words from words.txt and their values are the different anagrams for the 
# corresponding keys
def all_anagrams( filename ):
    # define a dictionary
    d = { }

    for w in open(filename):
        t = signature( w.strip().lower())
        if t not in d:
            d[t] = [ w.strip().lower() ]
            d[t].append( w.strip().lower() )

    return d 

#function to print contents of dictionary d
#that is, the list of anagrams previously stored in it 
def isAnagram(str1, str2):
    str1_list = list(str1)
    str2_list = list(str2)

    return (str1_list == str2_list)

# Let's test our solution
anagrams = all_anagrams("words.txt")
print_anagrams( anagrams)

['aah', 'aha']['aahed', 'ahead']['aal', 'ala']
This should be the output

0 Answers