Python,函数跳过条件

问题描述 投票:0回答:1

我复制了一个循环函数,根据输入的索引返回fibbonacci序列的值。

现在我想写一个函数 "tester() "来找到这个序列的第一个索引,它的计算花费了程序一定的毫秒数,当我输入例如3毫秒时,程序就会计算所有的东西,但在输出中显示程序至少是0毫秒。

def fib_loop(n):
start = int(datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]) #check system time when the function was initialize

n1, n2 = 1, 1
count = 0

if n == 1 or n == 2:
   return n1
else:
    while count < n-2:
        nth = n1 + n2
        # update values
        n1 = n2
        n2 = nth
        count += 1
    stop = int(datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]) #check system time on the end of the function
    time = stop - start  #compare times to get the milisecounds of function works
    return time 

def tester(miliseconds):
    x = 0
    while True:
        if fib_loop(x) <= miliseconds:
            x += 1
        else:
            return x, fib_loop(x)

print(tester(3))  #(2747, 0)

如你所见,当我输入3ms作为参数时,函数返回序列的第3000个左右的索引,但fib_loop(x)==0(fib_loop(x)返回这个函数至少花了多长时间),如果fib_loop(x)必须高于毫秒才能跳转返回,这怎么可能?

    if fib_loop(x) <= miliseconds:
        x += 1
    else:
        return x, fib_loop(x)

PS:当我给函数tester()传递一个较大的参数时,比如10,它的返回值是+- 7.你能告诉我为什么会发生这种情况吗?提前非常感谢你,真的很抱歉我的英语。

python skip
1个回答
1
投票

这是你要找的,我添加了一个函数包装器的时间执行,更多信息谷歌 "python装饰器"。

import time

# wrapper function for decorating fib_loop
def time_func(func):
    def wrapper(*args, **kwargs):
        start = time.time() * 1000 # unix timestamp
        func(*args, **kwargs) # <------- fib_loop here
        stop = time.time() * 1000
        return stop - start
    return wrapper


@time_func # execute fib_loop wrapped in the operations above
def fib_loop(n):
    n1, n2 = 1, 1
    count = 0
    if n == 1 or n == 2:
        return n1
    else:
        while count < n-2:
            nth = n1 + n2
            # update values
            n1 = n2
            n2 = nth
            count += 1
            # removed timing from here

def tester(miliseconds):
    x = 0
    while True:
        duration = fib_loop(x)
        data = {x: duration} # format the data as a dictionary, just because
        if duration <= miliseconds:
            print(data)
            x += 1
        else:
            print('')
            return data # return the index and duration of the first sequence above the threshold

print(tester(3))
© www.soinside.com 2019 - 2024. All rights reserved.