【问题标题】:How can I make this python function run O(log n) time instead of O(n) time?如何让这个 python 函数运行 O(log n) 时间而不是 O(n) 时间?
【发布时间】:2017-08-13 15:04:16
【问题描述】:
def findMax(f,c):
    n=1
    while f(n) <= c:
        n += 1
   return n

这是一个给定函数 f 和最大计数的高阶 python 函数, c 返回满足 f(n) ≤ c 的最大 n。这有效,但当 n 变得太大时无效,例如 f(10**6)。如何使该算法运行 O(log n) 时间,以便使用以下函数促进 f(10**6)

def f(n):
    return math.log(n, 2)

【问题讨论】:

标签: python algorithm time-complexity divide-and-conquer


【解决方案1】:

n += 1 更改为n *= 2 以获得对数结果。

对数序列以 2 的倍数递增,并且是非线性,因此对数序列不递增 1。

【讨论】:

    【解决方案2】:

    使用搜索算法更快地找到解决方案。这是使用 jpe.math.framework.algorythems.brent 的实现,它是布伦特搜索算法的实现。

    import math
    import jpe
    
    import jpe.math.framework.algorythems
    
    def f(x):
        return math.log(x, 2)
    
    value = 9E2
    startVal = 1E300
    
    val = int(jpe.math.framework.algorythems.brent(f, a=0, b=startVal, val=value, mode=jpe.math.framework.algorythems.modes.equalVal)[0])#takes 37 iters
    
    print(val)
    

    或者在这个场景中使用这个 f:

    结果在 2**c 的 1 以内(c 传递给 findMax)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-23
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多