有多少步骤和bigO复杂性

2024-07-02 10:42:39 发布

您现在位置:Python中文网/ 问答频道 /正文

def percentBases(dnaStrand):
    cytosine = dnaStrand.count('C')
    guanine= dnaStrand.count('G')
    adenine= dnaStrand.count('A')
    thymine= dnaStrand.count('T')
    
    percentC = round(cytosine/len(dnaStrand)*100,2)
    percentG =  round(guanine/len(dnaStrand)*100,2)
    percentA = round(adenine/len(dnaStrand)*100,2)
    percentT = round(thymine/len(dnaStrand)*100,2)
    
 
    return(percentC, percentG, percentA, percentT)

我已经编写了这段简单的代码,并被要求使用big-O表示法记录大致的时间复杂度。我对big-O符号一无所知,但读完后我会猜测: T(n)=8 O(8)

如果我错了,请纠正我,并试着向我解释。谢谢


Tags: lendefcountbigroundcytosinethymineadenine
2条回答

函数执行8个操作,所有操作都需要固定的时间。 所以,T(n)=8

就big-o而言,您可以将其写成 T(n)=O(1)或O(c)

要理解函数的大O时间复杂性,您需要了解随着输入大小的变化,计算什么需要更多的时间。您的输入dnaStrand是一个字符串,您执行两个操作countlen,随着输入长度的增加,这两个操作可能需要更多的时间^字符串的{}是常量(source),但count是线性的,因为必须在整个字符串上循环以计算不同子字符串的出现次数。所以,你的函数是4*O(n),或者仅仅是O(n)

相关问题 更多 >