【问题标题】:Simple way to count the number of times def f(x) is evaluated?计算 def f(x) 评估次数的简单方法?
【发布时间】:2015-10-23 23:26:58
【问题描述】:

我正在尝试计算 f(x) 被评估的次数,而不必过多地更改我的代码,看起来这应该不是很困难,但我似乎无法弄清楚。

def f (x):
    f = 12*x**5-45*x**4+40*x**3+5
    return f
def bounding():
    d=.1
    x=6
    n=0

while(n<50):
    Lb=x-d
    n+=1
    Ub=x+d
    if f(Lb)>=f(x) and f(Ub)<=f(x):
        x=x+d           
    elif f(Lb)<=f(x) and f(Ub)>=f(x):
        x=x-d           
    elif f(Lb)>=f(x) and f(Ub)>=f(x):
        print("Lower bound:",Lb,"Upperbound:",Ub)
        break
    print (n)
bounding()

【问题讨论】:

  • 我不确定你到底在问什么,但你的代码中有很多多余的东西,比如整个 bounding() 函数。
  • def f(x) 被计算时,函数被创建。这只会在您的代码中发生一次。你是指函数f被调用和执行的次数吗?

标签: python recursion numbers counting evaluation-strategy


【解决方案1】:

基于装饰器的解决方案,您可以将其应用于您想要的任何功能...

def count(fn):
        def wrapper(*args, **kwargs):
            wrapper.called+= 1
            return fn(*args, **kwargs)
        wrapper.called= 0
        wrapper.__name__= fn.__name__
        return wrapper

@count
def test():
    print "something"

test()

print test.called #will print 1

【讨论】:

  • 注意...这不需要更改您的功能...只需编写一个额外的装饰器...这完全在您的功能之外
  • 为什么不使用装饰器在代码中放一个示例?
  • @jpmc26:我不明白你的意思?我在我的示例中使用了装饰器:它称为 "count" ..@count ?
【解决方案2】:
class F:
    count = 0
    def __call__(self, x):
        self.count += 1
        return 12*x**5-45*x**4+40*x**3+5

f = F()

从这里开始和以前一样,计数由f.count 给出。测试:)

>>> f = F()
>>> f(1)
12
>>> f(2)
-11
>>> f.count
2
>>> f(2)
-11
>>> f.count
3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-15
    • 2012-05-08
    • 1970-01-01
    • 2014-03-24
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多