Home > Enterprise >  Why the function doesn't sucsses to sort the list right?
Why the function doesn't sucsses to sort the list right?

Time:11-23

I try to built a function that detact an anagrams is a list of word, and gave back a list of all the anagrams by their location in the first list. for example: input: ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts'] outpoot:[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'], ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'], ['smelters', 'termless', 'resmelts']]

my code is this:

def sort_anagrams(list_of_strings):
    #list_of_strings = tuple(list_of_strings)
    #print(list_of_strings)
    sorted_list_of_anagrams =[]
    
    for word_1 in list_of_strings:
        local_list = []
        if word_1 in local_list:
            for word_2 in list_of_strings:
                if is_anagrams(word_1, word_2) == True:
                    local_list.append(word_2)
        else:
            local_list.append(word_1)
            for word_2 in list_of_strings:
                if is_anagrams(word_1, word_2) == True:
                    local_list.append(word_2)
        local_list = sorted(local_list)
        if sorted(local_list) in sorted(sorted_list_of_anagrams):
            pass 
        else:
            sorted_list_of_anagrams.append(local_list)
    print(sorted_list_of_anagrams)                  
    #return sorted_list_of_anagrams
    

def is_anagrams(str_1, str_2):
    return str_1 != str_2 and sorted(str_1) == sorted(str_2)

def create_anagram_list(anagram_list):
    anagram_list = list(anagram_list)
    print(anagram_list)


first_list = ["deltas", "retainers", "desalt", "pants", "slated", "generating", "ternaries", "smelters", "termless", "salted", "staled", "greatening", "lasted", "resmelts"]
sort_anagrams(first_list)

it gave me back the anagrams but not in the right order. for example:['resmelts', 'smelters', 'termless'] instead of ['smelters', 'termless', 'resmelts']

CodePudding user response:

This was the problematic code:

        local_list = sorted(local_list)
        if sorted(local_list) in sorted(sorted_list_of_anagrams):

Being that sorted_list_of_anagrams is a list of lists when you sort it it doesn't sort every inner list individually only the outer list. This should work:

if sorted(local_list) in [sorted(lst) for lst in sorted_list_of_anagrams]:

Also make sure to delete the line above it local_list = sorted(local_list).

  • Related