-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path06_is_anagram.py
More file actions
47 lines (34 loc) · 760 Bytes
/
06_is_anagram.py
File metadata and controls
47 lines (34 loc) · 760 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'''
Requires n log n time(since any comparison based sorting algorithm rquires at least n log n time to sort)
'''
# Method-1
s1 = "fairy tales"
s2 = "rail safety"
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
print(s1)
print(s2)
print(sorted(s1) == sorted(s2))
print("\n")
# Method-2
def is_anagram(s1, s2):
ht = dict()
if len(s1) != len(s2):
return False
for i in s1:
if i in ht:
ht[i] += 1
else:
ht[i] = 1
for i in s2:
if i in ht:
ht[i] -= 1
else:
ht[i] = 1
for i in ht:
if ht[i] != 0:
return False
return True
if __name__ == "__main__":
X = is_anagram(s1, s2)
print(X)