如何在 python 中编写一个函数,给定一个项列表和导数的值 x,即 returns 导数在该点的值

How to write a function in python, given a list of terms and a value x of a derivative, that returns the value of the derivative at that point

每一项都是一个元组,例如 2x^3 + 7x 是 (2,3), (7,1) 导数是 (6,2), (7,0)

当有常量时,必须删除常量。例如 (2,4), (13,0) 只会 return (2,4).

下面是找到导数并过滤掉任何常数的代码,例如 (13,0)

def find_derivative(function_terms):
    return [(term[0] * term[1], term[1] - 1)
           for i, term in enumerate(function_terms)
               if term[0] * term[1] != 0]

好的,现在 return 当提供我写的 x 值时,给定点的导数值

def derivative_at(function_terms, x):
    filtered = list(filter(find_derivative, function_terms))
    

    new_value = filtered[0]* x, * [1]
    return new_value

find_derivative(three_x_squared_minus_eleven) # [(6, 1)]
derivative_at(three_x_squared_minus_eleven, 2) # 12

这是我收到 TypeError

的地方
TypeErrorTraceback (most recent call last)
<ipython-input-12-5fd5c2308a87> in <module>
      1 find_derivative(three_x_squared_minus_eleven) # [(6, 1)]
----> 2 derivative_at(three_x_squared_minus_eleven, 2) # 12

<ipython-input-11-bc3316259675> in derivative_at(terms, x)
      9 def derivative_at(terms, x):
     10 
---> 11     filtered = list(map(find_derivative, terms))
     12     return filtered
     13 

<ipython-input-4-48549a955063> in find_derivative(function_terms)
      3 def find_derivative(function_terms):
      4     return [(term[0] * term[1], term[1] - 1)
----> 5            for i, term in enumerate(function_terms)
      6                if term[0] * term[1] != 0]

<ipython-input-4-48549a955063> in <listcomp>(.0)
      4     return [(term[0] * term[1], term[1] - 1)
      5            for i, term in enumerate(function_terms)
----> 6                if term[0] * term[1] != 0]

TypeError: 'int' object is not subscriptable

我把事情搞得太复杂了。 用于过滤掉任何常量的函数 find_derivative() 应用在代码的底部:

   find_derivative(three_x_squared_minus_eleven)

此代码过滤掉术语中的任何常量。

之后我使用了两个用户定义函数的组合:

def term_output(term, x):
    a =  term[0]
    b =  term[1] 
    x = x
    result =  a * x * b
    return result
    

def derivative_at(list_of_terms, x):
    outputs = list(map(lambda term: term_output(term, x), list_of_terms))
    return sum(outputs)

find_derivative(three_x_squared_minus_eleven) # ([6,1])
derivative_at(three_x_squared_minus_eleven, 2) # 12

Derivative_at() 传递了现在过滤的 three_x_squared_minus_eleven 参数和 returns 我们的答案 12.