In this practice problem I don’t understand the solution to the part dealing with the auxiliary function. The aim was to create a frequency table of the characters in a string. I have commented on what is confusing me below.
Code:
def frequency(string):
freq = {}
for c in string:
if c not in freq:
freq[c] = 0 # Why is this not freq[c] = 1
freq[c] += 1
return freq
frequency('aaabbc') #Why does this not return {a:2 , b: 1, c:0} based on
#line 5 of this block of code.
Hello
even with the solution provided i am still facing problem. can you help?
def character_freq(string):
freq = {}
for c in string:
if c not in freq:
freq[c] = 0
else:
freq[c] += 1
return freq
def are_anagrams(string1, string2):
if len(string1) != len(string2):
return False
freq1 = character_freq(string1)
freq2 = character_freq(string2)
for c in freq1:
if c not in freq2 or freq1[c] != freq2[c]:
return False
return True
print(are_anagrams('gainly', 'laying'))
print(are_anagrams('banana', 'bacana'))
Hello,
The output is supposed to be: True False
And also I got this message from the system when i am trying to submit: Function are_anagrams did not return the expected value.
With this code provided my output is True True
So something is wrong
Thank you
Problem seems to indentation (the return statement) in are_anagrams function. It should be
def are_anagrams(string1, string2):
if len(string1) != len(string2):
return False
freq1 = character_freq(string1)
freq2 = character_freq(string2)
for c in freq1:
if c not in freq2 or freq1[c] != freq2[c]:
return False
return True
We can see that whatever kind of re-arrange position element in a string is, if one is an anagram, the element in the string isn’t replaced by any different element, it means that the exists of element in string is the same but only position change
So I use set condition to check that, here is my code:
I dunno why, because while we can go with a easier way, did we have any edge case that make this function is error? Because I check with the provided input and the result is OK