python – 为什么pow(x,y)的时间复杂度为O(1),而x ** y为O(n)?
为什么pow(x,y)的时间复杂度为O(1),而x ** y为O(n)? 查看agf here的评论 解决方法声明是错误的.> pow或多或少与**相同. 更多详细信息(来自于Stack Overflow上的other questions,以及Python源代码中的一些内容): > pow(参见here)和**(参见here)都调用相同的PyNumber_Power函数.在实践中,**可以更快,因为它避免了额外的符号查找和函数调用的开销. 如果您想自己玩这些命令,可以将这些命令粘贴到您的IPython会话中: import timeit def show_timeit(command,setup): print(setup + '; ' + command + ':') print(timeit.timeit(command,setup)) print() # Comparing small integers show_timeit('a ** b','a = 3; b = 4') show_timeit('pow(a,b)','a = 3; b = 4') show_timeit('math.pow(a,'import math; a = 3; b = 4') # Compare large integers to demonstrate non-constant complexity show_timeit('a ** b','a = 3; b = 400') show_timeit('pow(a,'a = 3; b = 400') show_timeit('math.pow(a,'import math; a = 3; b = 400') # Compare floating point to demonstrate O(1) throughout show_timeit('a ** b','a = 3.; b = 400.') show_timeit('pow(a,'a = 3.; b = 400.') show_timeit('math.pow(a,'import math; a = 3.; b = 400.') (编辑:甘南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |