Two strings are anagram if all letters in one string is also there in the other and vice versa
There are three anagram logics here:
if sorted(a)==sorted(b):
return True
if len(a) != len(b):
return False
else:
temp_dict = {}
for l in a:
if l in temp_dict:
temp_dict[l] += 1
else:
temp_dict[l] = 1
for l in a:
if l in temp_dict:
temp_dict[l] -= 1
else:
temp_dict[l] = 1
for l in temp_dict:
if temp_dict[l]!=0:
return False
return True
a1=list(a)
b1=list(b)
if len(a) != len(b):
return False
else:
index = 0
for idx, val in enumerate(a):
try:
b1.pop(idx)
a1.pop(0)
except:
return False
return True
a = "Public Relations"
b = "Crap Built on Lies"
a = a.replace(" ", "").lower()
b = b.replace(" ", "").lower()
%timeit one(a,b)
%timeit two(a,b)
%timeit three(a,b)
As you can see, first method that is Using Sorted is the most effective one. It is also the most readable code.
There are three anagram logics here:
Using Sorted
def one(a, b):if sorted(a)==sorted(b):
return True
Using Dictionary
def two(a,b):if len(a) != len(b):
return False
else:
temp_dict = {}
for l in a:
if l in temp_dict:
temp_dict[l] += 1
else:
temp_dict[l] = 1
for l in a:
if l in temp_dict:
temp_dict[l] -= 1
else:
temp_dict[l] = 1
for l in temp_dict:
if temp_dict[l]!=0:
return False
return True
Using List
def three(a,b):a1=list(a)
b1=list(b)
if len(a) != len(b):
return False
else:
index = 0
for idx, val in enumerate(a):
try:
b1.pop(idx)
a1.pop(0)
except:
return False
return True
a = "Public Relations"
b = "Crap Built on Lies"
a = a.replace(" ", "").lower()
b = b.replace(" ", "").lower()
%timeit one(a,b)
%timeit two(a,b)
%timeit three(a,b)
Output
100000 loops, best of 3: 2.96 µs per loop 100000 loops, best of 3: 4.93 µs per loop 100000 loops, best of 3: 4.74 µs per loopAs you can see, first method that is Using Sorted is the most effective one. It is also the most readable code.
Comments
Post a Comment