将具有单个或多个参数的函数传递给另一个函数

Passing a function with single or multiple arguments into another function

我正在对一些简单的阶乘算法进行算法 运行 时间分析,为了避免代码重复,我正在尝试创建一个单一的时间分析函数,它将不同的阶乘算法函数作为参数。

当我传入仅采用一个参数的阶乘函数(例如迭代函数)时,这工作正常,但作为我的作业的一部分,我还必须使用尾递归算法,它采用 2 个参数(n,累加器)。这是我的代码:

def iterFactorial(n):
    
    #running product
    factorial = 1
    
    #multiply each number in range 1 to n by the running product(i.e. the factorial)
    for i in range(1,n+1):
        
        factorial *= i
    #return the factorial
    return factorial 


def tail_Recur_Factorial(n,accumulator):
    
    if n == 1:
        return accumulator
    return tail_Recur_Factorial(n-1,n*accumulator)

running_times_1 = []
n_values = [i for i  in range(1,1000,100)]

def TimeAnalyis(function):
    
    #array for storing  multiple temporary running times of algorithm for a given n
    temp_time = [0]

    
    for n in n_values:
        
    
        #run fucntion 50 times for each given n value 
        for i in range(50):
            
            #take current timestamp
            start_time = time.time()
            
            #run function
            function(n)
            
            #take current timestamp
            end_time = time.time()
            
            #calculate time taken for function to run
            function_time = end_time - start_time
            
            #append to temp time array so mean can be taken
            temp_time.append(function_time)
            
        #take average running time
        running_times_1.append(statistics.mean(temp_time))
        
        #reset temp time
        temp_time = [0]

时间分析函数适用于迭代阶乘函数,我这样调用:

时间分析(iterFactorial)

我如何修改时间分析函数以允许我 ALSO 传入带两个参数的尾递归函数?

代码:

您可以为此创建装饰器。

def TimeAnalyis(func):
    #Takes any number of args and kwargs
    def wrapper(*args,**kargs):
        best = float('inf')
        for i in range(50):
            start = time.time()
            # Calls function and stores returned values in result
            result = func(*args,**kargs)
            total = time.time()-start
            if total<best:
                best = total
        # Print best timing
        print(f'Best time taken is {best} seconds')
        # returns the values returned by function
        return result
    # returns wrapper function
    return wrapper

#decorator
@TimeAnalyis
def anyfunc(n,m):
    for i in range(n):
         print(i*m)