Pythonic way to do `if x in y where x.attr == val`?

I have a class representing a polynomial as a set of members, where each member has a coefficient and exponent. I am working on a __add__class method , and I am wondering what is the most efficient way to do something like:

def __add__(self, other):
    new_terms = []
    for term in self.terms:
        if there is a term in other with an exponent == term.exponent
            new_terms.append(Term(term.coef + other_term.coef, term.exponent))

It seems to me that I'm looking for something like:

if x in y where x.attr == val

Or in my particular case:

if x in other where x.exponent == term.exponent

Is there such a thing?

+4
source share
2 answers

You need to filter your list before you check. As suggested by tobias_k, you can either create a new list, for example.

[x for x in other if x.exponent == term.exponent]

This works directly in the statement ifbecause the list is empty False:

if [x for x in other if x.exponent == term.exponent]:

- , : ) ) , . :

(True for x in other if x.exponent == term.exponent)

, if, :

if next((True for x in other if x.exponent == term.exponent), False):
+2

, [x for x in y if x.attr == val], next .

:

def __add__(self, other):
    for term in self.terms:
        for other_term in (x for x in other.terms 
                             if x.exponent == term.exponent):
            term.coefficient += other_term.coefficient

. -, __add__ self, other, . , other, , self. , -, , other self, .


, . collections.Counter; __add__ . - :

class Poly:

    def __init__(self, counts):
        self.terms = collections.Counter(counts)

    def __add__(self, other):
        return Poly(self.terms + other.terms)

    def __str__(self):
        return " + ".join("%dx^%d" % (c, x) for x, c in self.terms.items())

:

>>> Poly({2: 1, 1: 3, 0: 5}) + Poly({3: 1, 1: 2, 0: 3})
8x^0 + 5x^1 + 1x^2 + 1x^3
0

Source: https://habr.com/ru/post/1607666/


All Articles