This is my first code:
JavaScript
x
8
1
def isAnagram(s,t):
2
if len(s)!=len(t):
3
return False
4
for i in s:
5
if s.count(i)!=t.count(i):
6
return False
7
return True
8
This is my second code:
JavaScript
1
8
1
def isAnagram(s,t):
2
if len(s)!=len(t):
3
return False
4
for i in set(s):
5
if s.count(i)!=t.count(i):
6
return False
7
return True
8
This is my third code:
JavaScript
1
8
1
def isAnagram(s,t):
2
if len(s)!=len(t):
3
return False
4
for i in set(s[:]):
5
if s.count(i)!=t.count(i):
6
return False
7
return True
8
I don’t understand why replacing s
with set(s)
in 4th line takes less time to execute and replacing with set(s[:])
is even more better than the other two statements.
Can anyone help me to know why this happens?
Advertisement
Answer
After performing %timeit
I found that @Barmar observation is correct. You should perform timeit on these function.
set(s[:])
is expensive as compared to set(s)
For these 4 functions:
JavaScript
1
41
41
1
def isAnagram(s,t):
2
if len(s)!=len(t):
3
return False
4
a = set(s)
5
for i in a:
6
if s.count(i)!=t.count(i):
7
return False
8
return True
9
10
def isAnagram1(s,t):
11
if len(s)!=len(t):
12
return False
13
a = set(s[:])
14
for i in a:
15
if s.count(i)!=t.count(i):
16
return False
17
return True
18
19
def isAnagram2(s,t):
20
if len(s)!=len(t):
21
return False
22
for i in set(s):
23
if s.count(i)!=t.count(i):
24
return False
25
return True
26
27
def isAnagram3(s,t):
28
if len(s)!=len(t):
29
return False
30
for i in set(s[:]):
31
if s.count(i)!=t.count(i):
32
return False
33
return True
34
35
a = "abcde"
36
b = "edabc"
37
%timeit isAnagram(a, b)
38
%timeit isAnagram1(a,b)
39
%timeit isAnagram2(a,b)
40
%timeit isAnagram3(a,b)
41
I got following output:
JavaScript
1
5
1
958 ns ± 5.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
2
1.01 µs ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
3
967 ns ± 9.61 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
4
987 ns ± 2.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
5
Also fastest method to check anagram will be XOR operator.
JavaScript
1
6
1
def isAnagramXOR(s, t):
2
res = 0
3
for i,j in zip(s, t):
4
res ^= ord(i) ^ ord(j)
5
return not bool(res)
6
Performance: 667 ns ± 2.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)