Finding anagrams in Python -
i solved problem following way in python:
s1,s2 = raw_input().split() set1 = set(s1) set2 = set(s2) diff = len(set1.intersection(s2)) if(diff == 0) print "anagram!" else: print "not anagram!"
it seemed fine me. professor's program said i'm missing edge cases. can think of edge cases might have missed?
the correct way solve count number of characters in both strings , comparing each of them see if characters same , counts same.
python has collections.counter
job you. so, can do
from collections import counter if counter(s1) == counter(s2): print "anagram!" else: print "not anagram!"
if don't want use counter
, can roll own version of it, normal dictionaries , compare them.
def get_frequency(input_string): result = {} char in input_string: result[char] = result.get(char, 0) + 1 return result if get_frequency(s1) == get_frequency(s2): print "anagram!" else: print "not anagram!"
Comments
Post a Comment