Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create lists of anagrams from a list of words [duplicate]

I want to find create lists of anagrams from a list of words. Should I use another loop in my code or recursion?

some_list = ['bad', 'app', 'sad', 'mad', 'dab','pge', 'bda', 'ppa', 'das', 'dba']

new_list = [some_list[0]]
i = 0
while i+1 < len(some_list):
    if (''.join(sorted(some_list[0]))) == (''.join(sorted(some_list[i+1]))):
        new_list.append(some_list[i+1])
        i = i+1
    else:
        i = i+1

print(new_list)

  • My output is ['bad', 'dab', 'bda', 'dba']. But I also want more lists of other anagrams from some_list.

I want the output to be: - ['app', 'ppa'] - ['bad', 'dab', 'bda', 'dba'] - ['sad', 'das']

like image 979
pk. Avatar asked Sep 08 '25 12:09

pk.


1 Answers

I recommend you write Python, not Java or whatever other language you're emulating there. Here's your core code in Python, with normal looping and without all the unnecessary stuff:

new_list = [some_list[0]]
for word in some_list[1:]:
    if sorted(some_list[0]) == sorted(word):
        new_list.append(word)

I don't see use for recursion, but yes, you could wrap an outer loop around this to find the other anagram groups.


Though this is how I'd do it, using the helpful itertools.groupby:

for _, group in groupby(sorted(some_list, key=sorted), sorted):
    group = list(group)
    if len(group) > 1:
        print(group)

That prints:

['bad', 'dab', 'bda', 'dba']
['sad', 'das']
['app', 'ppa']

Alternative solution for the changed question with sorting the groups:

groups = (list(group) for _, group in groupby(sorted(some_list, key=sorted), sorted))
print([group for group in sorted(groups) if len(group) > 1])

Output:

[['app', 'ppa'], ['bad', 'dab', 'bda', 'dba'], ['sad', 'das']]
like image 96
Stefan Pochmann Avatar answered Sep 11 '25 05:09

Stefan Pochmann