File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ #anagram is where both the strings have each characters of the same frequency
2+ #danger and garden is an example of an anagram
3+
4+ def isanagram (s1 ,s2 ):
5+ if (len (s1 )!= len (s2 )):
6+ return False
7+
8+ # return sorted(s1) == sorted(s2)
9+ freq1 = {} #declaring dictionaries for mapping purpose
10+ freq2 = {}
11+
12+ #using dictionary(hash table) for assigning the character as key and no of times it repeated as values
13+ # {
14+ # char1:value1
15+ # }
16+ for char in s1 :
17+ if char in freq1 :
18+ freq1 [char ] += 1
19+ else :
20+ freq1 [char ] = 1
21+
22+ for char in s2 :
23+ if char in freq2 :
24+ freq2 [char ] += 1
25+ else :
26+ freq2 [char ] = 1
27+
28+ # for every key in dictionary freq1 we are comparing it with the key in dictionary freq2
29+ # if the key is not found then it will return false
30+ # and simillarly the values from both the dictionaries are being compared
31+ # if any one of the condition is false it will return false "or" is being used
32+ for key in freq1 :
33+ if key not in freq2 or freq1 [key ]!= freq2 [key ]:
34+ return False
35+ return True
36+
37+
38+
39+ s1 = input ("Enter a string\n " )
40+ s2 = input ("Enter second string\n " )
41+
42+ if isanagram (s1 ,s2 ):
43+ print (f"\n The { s1 } and { s2 } are Anagrams" )
44+ else :
45+ print (f"{ s1 } and { s2 } are not anagram" )
You can’t perform that action at this time.
0 commit comments