Here is my problem:
Here is my code:
And this is the error:
Here is my problem:
Here is my code:
And this is the error:
Okay, take the following input, and you will see why this fails
print(scramble('scriptingjavx','javascript'))
Your app will return true, but it is wrong. As there is only 1 ‘a’ in str1
To update your app, alter your IF statement to remove the letter it just found.
for i in s2:
if i not in s1:
b.append( False)
else:
b.append (True)
s1.remove(i)
That way, when it comes across the second ‘a’ in str2
, it can’t find such a character in str1
The code worked but somehow its taking a lot of time.
How can I reduce the time ?
Hmm, I didn’t get that previously. I wonder if you attempt it later on if it will be successful.
However, I guess the following approach is more efficient
from collections import Counter
def scramble(str1, str2):
str1= Counter(str1)
str2 = Counter(str2)
return all(str2[i] <= str1[i] for i in str2)
It makes use of Counter, which will count the number of times a letter is used in each word, if the number of times do not match, it fails. The all() is telling it all of the letters must have enough of a matching count found in str1 for it to pass.
This is what I am getting.
I did not get what “all” does here?
My bad, I had a typo, this is the correct version
from collections import Counter
def scramble(str1, str2):
str1= Counter(str1)
str2 = Counter(str2)
return all(str2[i] <= str1[i] for i in str2)
all, is validating that each letter found in str2 has enough matches in str1. Let’s take the prior example of scramble('scriptingjavx','javascript')
, there are two occurrences of ‘a’ in str2 and one in str1, so all would cause this to fail because str2[i] <= str1[i]
or 2 <= 1
equals False
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.