repl.it
@charles2588/

AnagramTester

Python

No description

fork
loading
Files
  • main.py
main.py
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
#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