-4

I am trying to print out the anagrams in a given list. I am unable to arrive at the right answer. I'd like to know where I am going wrong, and how can I fix it.

words = ['bat', 'rats', 'god', 'dog', 'cat', 'arts', 'star']
sort_words = []
anagrams = []
for word in words:
    word.split()
    word = ' '.join(sorted(word))
    sort_words.append(word)

for i in range(len(sort_words)):
    for j in range(len(sort_words)):
        if sort_words[i] == sort_words[j]:
            anagrams.append(sort_words[i])

print anagrams
KeerthiP
  • 11
  • 1
  • 5

3 Answers3

1

Here is a corrected version

words = ['bat', 'rats', 'god', 'dog', 'cat', 'arts', 'star']
sort_words = {}
for word in words:
    sort_words[word] = ''.join(sorted(word))

print sort_words
anagrams = []
for i in range(len(words)):
    ana = [words[i]]
    for j in range(i + 1, len(words)):
        if sort_words[words[i]] == sort_words[words[j]]:
            ana.append(words[j])
    if len(ana) != 1:
        anagrams.append(ana)

print anagrams

It outputs:

[['rats', 'arts', 'star'], ['god', 'dog'], ['arts', 'star']]
malbarbo
  • 10,717
  • 1
  • 42
  • 57
1

Well first you should have a different list for each word instead of a big list with everithing in. Let's try with a dictionnary:

words = ['bat', 'rats', 'god', 'dog', 'cat', 'arts', 'star']
sort_words = []
anagrams = {}
for word in words:
    word.split()
    word = ''.join(sorted(word))
    sort_words.append(word)

for i in range(len(sort_words)):
    word_anagram = []
    for j in range(len(sort_words)):
        if i == j:
            continue
        if sort_words[i] == sort_words[j]:
            word_anagram.append(words[j])
    anagrams[words[i]] = word_anagram 
print anagrams

Output:

{'bat': [], 'rats': ['arts', 'star'], 'god': ['dog'], 'arts': ['rats','star'], 'dog': ['god'], 'star': ['rats', 'arts'], 'cat': []}

You also forgot an important point: passing the i==j case which contaminate you result.

Vince
  • 336
  • 1
  • 11
0

To find the anagrams in a given list:

strs=['bat', 'rats', 'god', 'dog', 'cat', 'arts', 'star'] liste=[] 
sonuc=[] 
anagrams=[] 
for i in strs: 
  if sorted(i) not in liste:
    liste.append(sorted(i)) 
for i in range(len(liste)):
  sonuc.append([k for k in strs if sorted (k)==liste[i]]) anagrams.append([i for i in sonuc if len(i)>=2]) 
print(anagrams)
 
[[['rats', 'arts', 'star'], ['god', 'dog']]]
karel
  • 5,489
  • 46
  • 45
  • 50