Skip to content

Commit fec5210

Browse files
committed
added anagram.py
1 parent f3dabfe commit fec5210

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

an4gram.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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"\nThe {s1} and {s2} are Anagrams")
44+
else:
45+
print(f"{s1} and {s2} are not anagram")

0 commit comments

Comments
 (0)