Reputation: 39
I have a function that takes a string that counts the individual characters and puts the character along with the amount of time it shows up into a string. E.g:
isanagram("surfer")
returns
w1 = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 1, 'f': 1, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 2, 's': 1, 't': 0, 'u': 1, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0}
Although when I compare this function with two different parameters the print statement outputs True instead of False, which it clearly should be. Could anyone take a look. Here is my code:
alphabetlist = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
alphabetdict = {}
newalphadict = {}
def isanagram(aword):
for i in alphabetlist:
count = word.count(i)
alphabetdict[i] = count
return alphabetdict
print(isanagram("computer") == isanagram("science")) #outputting True. Should be outputting False.
Upvotes: 0
Views: 53
Reputation: 11171
There are a few issues with your code. Here is a better version:
from collections import Counter
def is_anagram(word1, word2):
c1 = Counter(word1)
c2 = Counter(word2)
return c1 == c2
is_anagram("computer", "science") # False
This solves the following issues with your current code:
newalphadict
, alphabetdict
reside outside your function, so letters get added to them every time isanagram
is called (a bug)is_anagram
compares two words. It should probably take two words as arguments (and nothing else).aword
!= word
Upvotes: 1
Reputation: 59
alphabetlist = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def isanagram(word=''):
alphabetdict = {}
for i in alphabetlist:
count = word.count(i)
alphabetdict[i] = count
return alphabetdict
print(isanagram("computer") == isanagram("science")) #-> False
Upvotes: 1