This is a website Question on Hackrrank called Hash Tables: Ransom Note:
Given the words in the magazine and the words in the ransom note, print "Yes" if we can replicate the ransom note exactly using whole words from the magazine; otherwise, print "No".
Here is an example input:
6 4
give me one grand today night
give one grand today
Output: Yes
And another:
6 5
two times three is not four
two times two is four
Output: No
def checkMagazine(magazine, note):
#Creating 2 Empty Dictionaries for the "Magazine" and the "Note" then filling them up
UniqueWordsMag = set(magazine)
UniqueCountMag = [0]*len(UniqueWordsMag)
UniqueWordDictMag = dict(zip(UniqueWordsMag, UniqueCountMag))
UniqueWordsNote= set(note)
UniqueCountNote = [0]*len(UniqueWordsNote)
UniqueWordDictNote = dict(zip(UniqueWordsNote, UniqueCountNote))
for i in magazine:
if i in list(UniqueWordDictMag.keys()):
UniqueWordDictMag[i] += 1
for i in note:
if i in list(UniqueWordDictNote.keys()):
UniqueWordDictNote[i] += 1
#Checking for existance in the magazine then checking for the correct count, print no if it does not fulfil conditions
Success = False
DesiredCount = len(note)
Count = 0
for index,i in enumerate(UniqueWordsNote):
if i in list(UniqueWordDictMag.keys()):
if UniqueWordDictNote[i] <= UniqueWordDictMag[i]:
Count += UniqueWordDictNote[i]
else:
break
else:
break
if Count == DesiredCount:
Success = True
print("Yes")
else:
print("No")
It's called from this main
program, that's provided by the challenge:
def main(): mn = input().split() m = int(mn[0]) n = int(mn[1]) magazine = input().rstrip().split() note = input().rstrip().split() checkMagazine(magazine, note) if __name__ == "__main__": main()
My code is currently taking too long on some lists (e.g. lists of size 30,000 or more). Are there any optimisations I can make to make this a bit more legible and faster?
snake_case
instead ofcamelCase
. \$\endgroup\$