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)
['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']
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With