Filtering out specific terms

我只是一个虾纸丫 提交于 2019-12-13 03:39:55

问题


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_term

def find_derivative(function_terms):
    new_function = []
    for term in function_terms:

        new_term = find_term_derivative(term)
        new_function.append(new_term)

        filtered_terms = filter(zero_filter, new_term)

find_derivative[(4, 3), (-3, 1)]

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

However I want to use the filter function to remove any terms which output begin with zero.

For example Inputs [(3, 2), (-11, 0)] Currently Outputs [(6, 1), (0, -1)]

However I want to filter & remove the second term because it begins with 0, removing it from the dictionary new_function

I am trying to define a filter function which analyses the first term of each tuple and checks if its 0, and removes it if is. Is this how the filter function is used?

def zero_filter(variable):
    if new_term [0] = 0:
        return False 
    else:
        return True

回答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.

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

def find_derivative(function_terms):
    new_function = []
    for term in function_terms:
        new_term = find_term_derivative(term)
        new_function.append(new_term)
    return list(filter(zero_filter, new_function))

def zero_filter(atuple):
    """Note if the first element of a tuple is non-zero
    or any truthy value."""
    return bool(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.



来源:https://stackoverflow.com/questions/56666683/filtering-out-specific-terms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!