The Count and Compare Anagram solution provided at interactivepython.org checks iterates through the lists for a final time checking if the count for each ASCII value is the same.
j = 0
stillOK = True
while j<26 and stillOK:
if c1[j]==c2[j]:
j = j + 1
else:
stillOK = False
return stillOK
Why not use the comparison operator?
return (c1 == c2)
Full code:
def anagramSolution4(s1,s2):
c1 = [0]*26
c2 = [0]*26
for i in range(len(s1)):
pos = ord(s1[i])-ord('a')
c1[pos] = c1[pos] + 1
for i in range(len(s2)):
pos = ord(s2[i])-ord('a')
c2[pos] = c2[pos] + 1
j = 0
stillOK = True
while j<26 and stillOK:
if c1[j]==c2[j]:
j = j + 1
else:
stillOK = False
return stillOK
print(anagramSolution4('apple','pleap'))
Edited to add:
I've tested with:
anagramSolution4('abc','cba') #returns True
anagramSolution4('abc','cbd') #returns False
anagramSolution4('abc','cbah') #returns False
..they all pass. What would be an appropriate test to show c1==c2 fails?
Using ==
on the two lists would produce the same result, but would also hide some implementation details. Given that the script comes from a website used for learning, I guess this is for learning purposes.
Also, I see that in the webpage you are asked some questions about complexities. Well, using c1 == c2
instead of the loop would probably mislead some people and make them think that the operation is O(1) instead of O(min(len(c1), len(c2)))[1].
Finally, note that there are many languages which have no notion of lists.
[1] This isn't necessarily true either, as the two lists may contain items with custom and complex __eq__()
methods.