Trying to come up with python anagram function

2020-04-21 08:23发布

What I'm trying to do is if I have a list like:

["lime", "mile", "liem", "tag", "gat", "goat", "math"]

I want to write a function that returns the words in the list that have an anagram, which would look like:

["lime", "mile", "liem", "tag", "gat",]

So far I have this code:

def anagramprinter(x):

    output = []     
    for i in x:
        for n in i:
            if n in x[i]:

I can't past this part and would like some help and would also appreciate a thorough explanation as well.

Can anyone please show me a way that doesn't involve importing? Thanks

Thanks.

7条回答
姐就是有狂的资本
2楼-- · 2020-04-21 09:12

You can use itertools to create all permutations of the words, remove the word you just found the permutations of, and then check your list one word at a time to see if it is in permutations like so

from itertools import permutations

l = ["lime", "mile", "liem", "tag", "gat", "goat", "math"]
final = []
perms = []
for i in l:
    perms += [''.join(p) for p in permutations(i)]
    perms.remove(i)

for i in l:
    if i in perms:
        final.append(i)
print final

This isn't the fastest solution in the world, especially if you have long words like 'resistance', 'ancestries'

查看更多
登录 后发表回答