0

I want to write a function that finds anagrams. Anagrams are words that are written with the same characters. For example, "abba" and "baba".

I have gotten as far as writing a function that can recognize if a certain string has the same letters as another string. However, I can't account for the number of repeated letters in the string.

How should I do this?

This is the code I have written so far:

def anagrams(word, words):
    list1 = []
    for i in words:
        if set(word) == set(i):
            list1.append(i)      
    return list1

The inputs look something like this:

('abba', ['aabb', 'abcd', 'bbaa', 'dada'])

I want to find an anagram for the first string, within the list.

António Rebelo
  • 186
  • 1
  • 13

1 Answers1

1

You kind of point to the solution in your question. Your current problem is that using a set, you ignore the count of times each individual letter is contained in the input and target strings. So to fix this, start using these counts. For instance you can have a mapping between letter and the number of its occurrences in each of the two strings and then compare those mappings.

For the purposes of learning I would like to encourage you to use dict to solve the problem. Still after you know how to do that, there is a built-in container in collections, called Counter that can do the same for you.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176