首页 > 解决方案 > 在查找导数时,如何在 python 3 中使用 filter 函数仅返回导数未乘以零的项?

问题描述

我写了一个函数,给定方程的项,可以找到导数。但是,当其中一项为零时,该功能就会失效。我将如何使用过滤器来确保乘以零的项不会返回?

这是我的基线代码,它有效但不包含过滤器:

def find_derivative(function_terms):
    return [(function_terms[0][0]*function_terms[0][1], function_terms[0][1]-1),(function_terms[1][0]*function_terms[1][1], function_terms[1][1]-1)]

function_terms[1][1]-1 将导数项的幂降低 1。

它是这样工作的。

输入:

# Represent each polynomial term with a tuple of (coefficient, power)

# f(x) = 4 x^3 - 3 x
four_x_cubed_minus_three_x = [(4, 3), (-3, 1)]
find_derivative(four_x_cubed_minus_three_x)  

输出:

[(12, 2), (-3, 0)]

这是正确答案12 x^2 - 3

但在这里它崩溃了:

输入:

# f(x) = 3 x^2 - 11
three_x_squared_minus_eleven = [(3, 2), (-11, 0)]                       
find_derivative(three_x_squared_minus_eleven) 

给定方程,它应该找到导数。

输出:

((6, 1), (0, -1))

这有一个“幽灵”术语0 * x^(-1);我不想打印这个词。

预期输出:[(6, 1)]

标签: pythonderivative

解决方案


您可以使用该filter()函数过滤元组列表,然后在过滤后的列表上应用逻辑。像这样的东西应该工作。

filtered_terms = list(filter(lambda x: x[1]!=0, function_terms))

现在你有了没有常量的元组。因此,与其对导数进行硬编码,不如尝试遍历列表以获取导数。

result = []
for term in filtered_terms:
    result.append((term[0]*term[1], term[1]-1))
return result

推荐阅读