Search code examples
pythondictionaryderivativepolynomials

How to change key-value in dictionary using dictionary comprehension + if/else?


I'm given a dictionary with exponents-coefficients as key-value pairs for polynomials. My task is to make a function to return a dictionary containing the derivative exponents-coefficients key-value pairs. This is what I have got so far, but it is not working:

def diff_p(d):
    d = {i - 1: i*d[i] if i is not 0 else d[i]: 0 for i in d}
    return d

p = {0: -3, 3: 2, 5: -1}

Why do I get syntax error? And can someone come up with a good remedy, preferably a one liner?

Update:

Thanks to Karl Knechtel's answer one can make this task into this neat one liner:

deff_p = lambda d: {e - 1: c*e for e, c in d.items() if e != 0}


Solution

  • i - 1: i*d[i] if i is not 0 else d[i]: 0
    

    The problem is that you are thinking of i - 1: i*d[i] and d[i]: 0 as single "terms" in the expression. They are not. You need to use separate conditional logic for both the key and the value.

    Also, you should use == and != for numeric comparison, not is and is not.

    So that would give you {(i - 1 if i != 0 else d[i]): (i*d[i] if i != 0 else 0) for i in d}. (It should work without the parentheses, but I think it's really hard to read that way.)

    That said, given that your dictionary represents the coefficients of a polynomial, and the function performs differentiation, I can't understand why you're putting in this weird special-cased term. Constant terms of polynomials are supposed to disappear entirely when you differentiate; the natural logic is therefore to filter that out entirely, like: {i - 1: i*d[i] for i in d if i != 0}.

    Finally, typically it's considered cleaner to iterate over the key-value pairs ("items") of the dictionary directly: {e - 1: c * e for e, c in d.items() if e != 0} (here I have written e for "exponent" and c for "coefficient").