首页 > 解决方案 > Python code to compute anagrams without reptetitions

问题描述

I am solving a python exercise that asks me to find all the possible anagrams of a word but excluding the anagrams that occur more then once.

Here is the code I have come up with:

    from itertools import permutations
seq = getString('Insert ')

seq = permutations(seq) # this let us get all anagrams WITH repetitions
unique = []
unique2=[]
for x in seq:
    unique.append(x)
i=0
while i < len(unique): 
    if unique[i] in unique[i+1:]:
        i=i+1
        continue
    if unique[i] not in unique[i+1:]:
        unique2.append(unique[i])
        i=i+1

What the while does is basically this: consider the ith-anagram and check if in the next part of the list there is an anagram that is identical to the one we are checking. If yes, increase the counter "i" and go on, otherwise append that anagram (that we are sure it does not have repetitions) to another new list.

This goes on up until we reach an i that has a lenght equal to the lenght of the list of permutations with repetitions.

标签: pythonanagram

解决方案


推荐阅读