Reputation: 65
I am trying to look for keys with similar letters (anagram) in an imaginary dictionay and I have this incomplete code:
from collections import Counter
diction = {'crazy':'dd', 'abd':'ddd','cat':'bad'}
word = input('what is the word?')
new=[]
for i in dic:
if(Counter(word) == Counter(....):
new.append(...)
else:
continue
print(f'{word} and {new} are anagrams')
I have no idea how to check for the keys and if they match the given input. Appreciate your help
Upvotes: 1
Views: 63
Reputation: 5590
I actually think Counter
is a good solution here, probably better than sorting because it is O(n). For example, Counter("arc") == Counter("car")
returns True
. So you were on the right track.
There are typos in your code (dic
should be diction
). Your for loop was already iterating through keys, so you were close:
from collections import Counter
diction = {'crazy':'dd', 'abd':'ddd','cat':'bad'}
word = input('what is the word?')
new=[]
for i in diction:
if(Counter(word) == Counter(i)):
new.append(i)
else:
continue
print(f'{word} and {new} are anagrams')
If I input "tac", it will print:
tac and ['cat'] are anagrams
Upvotes: 2