为什么这两段代码具有不同的复杂性?

时间:2019-12-01 13:56:22

标签: python compare complexity-theory

这两个代码段都执行相同的操作,即它们检查列表magazine_words中的单词是否足以构成列表note_words中的单词所指示的消息。但是,第一段代码需要花费更多的时间来执行,因此不允许其在大型输入上运行。这是为什么?由于两种解决方案都使用单个for循环,因此它们是否应该具有相同的复杂度,即运行大约相同的时间?

第一个解决方案:

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))

第二种解决方法:

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")```

1 个答案:

答案 0 :(得分:1)

magazine_words.remove(note_words[ind])是另一个秘密循环-每次调用它时,都必须循环遍历所有magazine_words直到找到note_words[ind]