I am working on a Leetcode problem, and currently the algorithm that I have passes 98/128 for the testcases. I created teo (2) dictionaries with counts of each occurence, and wrote a little bit to compare the two counts.
Here is what I have:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransomdict = {}
magadict = {}
for i in ransomNote:
if i in ransomdict:
ransomdict[i] +=1
else:
ransomdict[i] = 1
for j in magazine:
if j in magadict:
magadict[j] +=1
else:
magadict[j] = 1
print(ransomdict)
print(magadict)
for k in ransomdict:
if k in magadict:
if magadict[k] >= ransomdict[k]:
return True
else:
return False
I printed ransomdict and magadict, and clearly the counts are right. I know this code isn’t optomized; I’m just trying to get it to work at the moment.
This particular test case is supposed to return False, but it is returning true. I do have some tests passed where it is returning false.
You can simply use Counter()
and check Counter(ransomNote) <= Counter(magazine)
:
from collections import Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
return Counter(ransomNote) <= Counter(magazine)