在python3中,在求导数时,如何使用filter函数只返回导数不乘以零的项?

2024-04-18 23:21:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个函数,给定一个方程的项,可以求导数。但是,当其中一个项为零时,函数将崩溃。我如何使用过滤器来确保乘以零的项不会返回?你知道吗

下面是我的基线代码,它可以工作,但还不包括过滤器:

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)]

函数项[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)]


Tags: 函数过滤器functionfind术语threefour方程
3条回答

可以使用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

两个变化:

  1. 使您的例程遍历多项式项,一次处理一个,而不是依赖于只有两个项。你知道吗
  2. 在遇到单个术语时对其应用过滤。你知道吗

我扩展了它,也消除了系数为零,指数为零的任何东西。我添加了一个测试用例,其中都是负指数,因为符号微分定理同样适用。你知道吗

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 ]

four_x_cubed_minus_three_x = [(4, 3), (-3, 1)]
print(find_derivative(four_x_cubed_minus_three_x) )

three_x_squared_minus_eleven = [(3, 2), (-11, 0)]
print(find_derivative(three_x_squared_minus_eleven) )

fifth_degree = [(1, 5), (-1, 4), (0, 3), (8, 2), (-16, 0), (1, -2)]
print(find_derivative(fifth_degree) )

输出:

[(12, 2), (-3, 0)]
[(6, 1)]
[(5, 4), (-4, 3), (16, 1), (-2, -3)]

python中有一个符号数学解算器,名为sympy。也许对你有用。你知道吗

from sympy import *
x = symbols('x')
init_printing(use_unicode=True)

equation = 4*x**3 -3*x
diff_equation = equation.diff()
solution = diff_equation.subs({x:2})

相关问题 更多 >