Skip to content

Instantly share code, notes, and snippets.

@charles2588
Created June 28, 2016 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charles2588/62e2862ecd5eed6f6a764cbcfd544273 to your computer and use it in GitHub Desktop.
Save charles2588/62e2862ecd5eed6f6a764cbcfd544273 to your computer and use it in GitHub Desktop.
https://repl.it/C6t6/2 created by charles2588
#Test if strings are anagram provided their length is same.
def anagramtester(str1,str2):
#dictionary=dict(range(0,26))
#CountDict=dict((el,0) for el in str1)
CountDictStr1=dict()
# i need dictionary to keep count
for i in range(len(str1)):
if str1[i] in CountDictStr1.keys():
CountDictStr1[str1[i]]+=1
else:
#add the key and initialize Count
CountDictStr1[str1[i]]=1
CountDictStr2=dict()
# i need dictionary to keep count
for i in range(len(str2)):
if str2[i] in CountDictStr2.keys():
CountDictStr2[str2[i]]+=1
else:
#add the key and initialize Count
CountDictStr2[str2[i]]=1
for j in CountDictStr2.keys():
if j in CountDictStr1.keys():
if CountDictStr1[j]!=CountDictStr2[j]:
return False
else:
return False
return True
print(anagramtester("python","typhoe"))
print(anagramtester("python","typhon"))
#Above method is called "count and compare" Time complexity is O(n) since for each loop n to max 3n which is O(n)
#mind the space complexity in the above method is high
#Check off method can be use to save space using checking off each character we find.
#http://interactivepython.org/runestone/static/pythonds/AlgorithmAnalysis/AnAnagramDetectionExample.html
Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
>>> False
True
=> None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment