I wrote a function that, given the terms of an equation, can find derivatives. However when one of the terms is a zero, the function breaks down. How would I use filter to make sure terms that are multiplied by zero don't return?
Here's my baseline code which works but doesn't include the filter yet:
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)]
The function_terms[1][1]-1 reduces the power of the term of the derivative by 1.
It works like this.
Input:
# 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)
Output:
[(12, 2), (-3, 0)]
This is the correct answer of 12 x^2 - 3
But here it breaks down:
Input:
# f(x) = 3 x^2 - 11
three_x_squared_minus_eleven = [(3, 2), (-11, 0)]
find_derivative(three_x_squared_minus_eleven)
It is supposed to find the derivative, given the equation.
Output:
((6, 1), (0, -1))
This has a "ghost" term of 0 * x^(-1)
; I don't want this term printed.
Expected Output: [(6, 1)]
You can use the filter()
function to filter the list of tuples and then apply logic on the filtered list. Something like this should work.
filtered_terms = list(filter(lambda x: x[1]!=0, function_terms))
Now you have the tuples without constants. So rather than hard-coding derivatives, try looping through the list to get the derivative.
result = []
for term in filtered_terms:
result.append((term[0]*term[1], term[1]-1))
return result