Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何获得代码的大O时间复杂度?_Python_Time Complexity_Big O - Fatal编程技术网

Python 如何获得代码的大O时间复杂度?

Python 如何获得代码的大O时间复杂度?,python,time-complexity,big-o,Python,Time Complexity,Big O,我对大O符号有很好的理解,但我对这个问题很困惑: 给定一个包含N个元素的排序列表,并且要搜索的键在中重复R次 列表中,my_search()以O表示法的复杂性是多少 def my_搜索(数据、键): 发现=错误 低=0 计数=0 高=透镜(数据)-1 while(未找到且低位=0且数据[k]==键: 计数+=1 k-=1 k=猜测+1 当k

我对大O符号有很好的理解,但我对这个问题很困惑:

给定一个包含N个元素的排序列表,并且要搜索的键在中重复R次 列表中,my_search()以O表示法的复杂性是多少

def my_搜索(数据、键):
发现=错误
低=0
计数=0
高=透镜(数据)-1
while(未找到且低位=0且数据[k]==键:
计数+=1
k-=1
k=猜测+1
当k

该函数传递的参数是一个列表和一个键,该函数计算该键在列表中出现的次数,例如
my_search([1,1,2,2,3,3,3,3,6,7],1)
。答案键表示该代码的时间复杂度是,他们是如何得出这个答案的?

在有序列表中搜索是O(log(N))()。找到要查找的元素后,需要根据搜索的项目检查(至少)R个元素。因此,总计O(log(N))+R.

这个问题似乎更适合@Taegyung谢谢你的建议,我不知道CS堆栈交换,我下次会在那里发布,谢谢。我明白了,我很困惑,因为我认为log base 2(N)不同于log(N),但我猜不是。谢谢你!技术上它应该是log2(N),但作为log2(N)=log(N)/log(2)它们之间只有一个常数因子不同,这在讨论复杂性时是不相关的。我可能应该写log2。。。
def my_search( data, key ):
 found = False
 low = 0
 count = 0
 high=len(data)-1
 while ( not found and low<=high):
     guess = (high+low)//2
     print('guess: ', guess)
     if ( key == data[guess] ):
         found = True
         count = 1
         k = guess - 1
         while k>=0 and data [k] == key:
             count += 1
             k -= 1
         k = guess + 1
         while k < len(data) and data [k] == key:
             count += 1
             k += 1
     else:
         if (key < data[guess]):
             high=guess-1
         else:
             low = guess+1
 print('count:', count)
 return count