Trying to come up with python anagram function

后端 未结 7 2012
梦谈多话
梦谈多话 2021-01-23 14:02

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 functio

7条回答
  •  孤独总比滥情好
    2021-01-23 14:26

    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'

提交回复
热议问题