python - Create lists of anagrams from a list of words -


i want find create lists of anagrams list of words. should use loop in code or recursion?

some_list = ['bad', 'app', 'sad', 'mad', 'dab','pge', 'bda', 'ppa', 'das', 'dba']  new_list = [some_list[0]] = 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+1     else:         = i+1  print(new_list) 

  • my output ['bad', 'dab', 'bda', 'dba']. want more lists of other anagrams some_list.

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

i recommend write python, not java or whatever other language you're emulating there. here's core code in python, normal looping , without unnecessary stuff:

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

i don't see use recursion, yes, wrap outer loop around find other anagram groups.


though how i'd it, using 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 changed question sorting groups:

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

output:

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

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -