Created
July 7, 2018 01:49
-
-
Save roguesherlock/e2f2429c36b9df98ff828f78c4dfdba2 to your computer and use it in GitHub Desktop.
comparison between isAnagram function (one implemented using sorted and other with hashmaps)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import string | |
import timeit | |
def isAnagramSorted(str1, str2): | |
return sorted(str1) == sorted(str2) | |
def isAnagram(str1, str2): | |
stringMap = {} | |
for c in str1: | |
count = stringMap.get(c) or 0 | |
count += 1 | |
stringMap[c] = count | |
for c in str2: | |
count = stringMap.get(c) | |
if (count): | |
if (count < 1): | |
return False | |
count -= 1 | |
stringMap[c] = count | |
return True | |
def getAnagramStrings(strlen): | |
str1 = '' | |
for i in range(strlen): | |
str1 += string.ascii_letters[random.randint(0, 51)] | |
str2 = ''.join(random.sample(str1,len(str1))) | |
return (str1, str2) | |
if __name__ == '__main__': | |
for i in range(100, 1000, 100): | |
str1, str2 = getAnagramStrings(i) | |
print('---------------------------------------------\n') | |
print('strlen: {}'.format(i)) | |
print('isAnagram: {}'.format(timeit.timeit('isAnagram(str1, str2)', globals=globals(), number=1000))) | |
print('isAnagramSorted: {}'.format(timeit.timeit('isAnagramSorted(str1, str2)', globals=globals(), number=1000))) | |
print('---------------------------------------------\n') | |
for i in range(1000, 10000, 1000): | |
str1, str2 = getAnagramStrings(i) | |
print('---------------------------------------------\n') | |
print('strlen: {}'.format(i)) | |
print('isAnagram: {}'.format(timeit.timeit('isAnagram(str1, str2)', globals=globals(), number=1000))) | |
print('isAnagramSorted: {}'.format(timeit.timeit('isAnagramSorted(str1, str2)', globals=globals(), number=1000))) | |
print('---------------------------------------------\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment