6.3k views
3 votes
An anagram of a string is another string with the same characters in the same frequency, in any order. For example 'ab', 'bca, acb), 'bac', 'cba, 'cab' are all anagrams of the string 'abc'. Given two arrays of strings, for every string in one list, determine how many anagrams of it are in the other list. Write a function that receives dictionary and query, two string arrays. It should return an array of integers where each element i contains the number of anagrams of queryll that exist in dictionary.

1 Answer

1 vote

Answer:

from collections import Counter

def anagram(dictionary, query):

newList =[]

for element in dictionary:

for item in query:

word = 0

count = 0

for i in [x for x in item]:

if i in element:

count += 1

if count == len(item):

newList.append(item)

ans = list()

for point in Counter(newList).items():

ans.append(point)

print(ans)

mylist = ['jack', 'run', 'contain', 'reserve','hack','mack', 'cantoneese', 'nurse']

setter = ['ack', 'nur', 'can', 'con', 'reeve', 'serve']

anagram(mylist, setter)

Step-by-step explanation:

The Counter class is used to create a dictionary that counts the number of anagrams in the created list 'newList' and then the counter is looped through to append the items (tuple of key and value pairs) to the 'ans' list which is printed as output.

User Kosmos
by
5.6k points