Skip to content Skip to sidebar Skip to footer

Filtering Out Specific Terms

I have written a function that uses derivative product rule to find derivative of a term: def find_term_derivative(term): x , y = term new_term = (y*x, y-1) return new_

Solution 1:

Rather than writing a function that flags if a term should be filtered, just end your routine with a list comprehension that does the filtering.

filtered_list = [v for v in unfiltered_list if v[0]]

Your code has some other problems, but since you did not ask about them I'll not go into that. Change the variables in the line I showed you to fit into your routine.


If you need Python's filter function, you could use this.

deffind_term_derivative(term):
    x , y = term
    new_term = (y*x, y-1)
    return new_term

deffind_derivative(function_terms):
    new_function = []
    for term in function_terms:
        new_term = find_term_derivative(term)
        new_function.append(new_term)
    returnlist(filter(zero_filter, new_function))

defzero_filter(atuple):
    """Note if the first element of a tuple is non-zero
    or any truthy value."""returnbool(atuple[0])

print(find_derivative([(4, 3), (-3, 1)]))
print(find_derivative([(3, 2), (-11, 0)]))

The printout from that is what you want:

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

I did the non-zero check in the filter using the pythonic way: rather than check explicitly that the value is not zero, as in atuple[0] != 0, I just checked the "truthiness" of the value with bool(atuple[0]). This means that values of None or [] or {} or () will also be filtered out. This is irrelevant in your case.

By the way, I used the name zero_filter since you did, but that does not seem to me to be the best name. Perhaps filter_out_zeros would be better.

Post a Comment for "Filtering Out Specific Terms"