python - 在查找导数时,如何在 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)]
解决方案
您可以使用该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
推荐阅读
- php - 内部站点搜索仅匹配确切的单词
- javascript - 鼠标在jquery中移动时添加不同的图像
- woocommerce - Woocommerce - 根据人数计算额外费用
- c++ - 为什么我的代码会导致高返回值?C++
- android - 导航图 - 如何使用导航图和导航抽屉中的自定义片段来管理导航抽屉
- mysql - 带有 WHERE 子句的 MySQL SELECT 查询不从两个表中返回行
- javascript - 搜索表单多个字段 javascript
- angular - 超时 - 在 jest.setTimout.Timeout 指定的 10000 毫秒超时内不涉及异步回调
- r - ggplot:堆叠条形图 - geom_text 标签凌乱
- python - Wxpython将数据从一帧传递到另一帧