i can't see it. why my loop is not well !? please try to help me :)
def sort_anagrams(list_of_strings):
result = []
for i in range(len(list_of_strings)):
deleted_items = 0
templist = []
templist.append(list_of_strings[i])
for j in range(i+1, len(list_of_strings) - deleted_items):
print("*debug: i=", i, "j=", j, "len-list=", len(list_of_strings), "del-items=", deleted_items, "len-del=", len(list_of_strings) - deleted_items, "j-del = ", j-deleted_items)
if sorted(list(list_of_strings[i])) == sorted(list(list_of_strings[j - deleted_items])):
templist.append(list_of_strings[j - deleted_items])
print("~joined!", templist)
list_of_strings.remove(list_of_strings[j - deleted_items])
deleted_items += 1
result.append(templist)
print(result)
return result
list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']
print(sort_anagrams(list_of_words))
#result:
#[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'], ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'], ['smelters', 'termless', 'resmelts']]
the code should return a new list of list's that contain the original worlds from list_of_words, grouped by anagrams (word's with the same letters)
Now you determined how many
i
you will have. It is determined at this moment becauselen(list_of_strings)
gives you number, not reference to list lenght.Now you deleted something from the list, so at the end your list is shorter than starting
len(list_of_strings)
. Wheni
is bigger then current length of list python will raiseIndexError: list index out of range
.Try to loop over elements of list with: