Reputation: 27
Both of these pieces of code do the same thing, which is they check if the words in the list magazine_words
are sufficient to make up the message dictated by the words in the list note_words
. However the first piece of code takes a lot more time to execute, which doesn't let it run for large inputs. Why is that? Since both solutions use single for-loops, shouldn't they have the same complexity, i.e. take about the same time to run?
First solution:
lengths = input().split ()
m = int(lengths[0])
n = int(lengths [1])
magazine_words = input ().split()
note_words = input ().split()
def checkMagazine(m,n,magazine_words,note_words):
flag = "Yes"
for ind in range (n):
if not (note_words[ind] in magazine_words):
flag = "No"
break
else:
magazine_words.remove(note_words[ind])
return flag
print (checkMagazine(m,n,magazine_words,note_words))
Second solution:
def ransom_note(magazine, ransom):
rc = {} # dict of word: count of that word in the note
for word in ransom:
if word not in rc:
rc[word] = 0
rc[word] += 1
for word in magazine:
if word in rc:
rc[word] -= 1
if rc[word] == 0:
del rc[word]
if not rc:
return True
return False
m, n = map(int, input().strip().split(' '))
magazine = input().strip().split(' ')
ransom = input().strip().split(' ')
answer = ransom_note(magazine, ransom)
if(answer):
print("Yes")
else:
print("No")```
Upvotes: 0
Views: 23
Reputation: 2545
magazine_words.remove(note_words[ind])
is secretly another loop - this has to loop through all of magazine_words
until it finds note_words[ind]
, each time you call it.
Upvotes: 1