如何将循环重复一定次数以获得N次导数?

how to repeat a loop a certain number of times to get the Nth derivative?

我正在尝试获取字典中给出的多项式方程的系数和幂的 N 阶导数。在字典中,键是幂,值是给定多项式的系数。

这是我的代码,适用于一阶导数:

'''

def differentiate(polynomial, order):

        derivative = {}

        for power, coeff in poly.items():

            new_coeff = poly[power] * power

            new_power = power - 1

            derivative[new_power] = new_coeff

            if derivative[new_power] == 0:

                del derivative[new_power]

        return derivative

if __name__ == "__main__":  
        poly = {-5: 4.0, 2: 3.5, 1: 10.0}
        print(differentiate(poly, 2))  # {-7: 120.0, 0: 7.0}

'''

如何重复循环以获得 N 阶导数? 我尝试使用范围功能,但似乎无法正常工作。 有线索吗?

我就是这样处理的

def differentiate(polynomial, order):
    derivative = {}
    counter = 1
    _dict = polynomial

    while counter <= order:
        for power, coeff in _dict.items():
            new_coeff = _dict[power] * power
            new_power = power - 1
            derivative[new_power] = new_coeff
            if derivative[new_power] == 0:
                del derivative[new_power]
        counter += 1
        _dict = derivative
        derivative = {}
    return _dict