1

I have the following class:

class Node:  
    def __init__(self, node, value, left=None, right=None):
        self.node = node    
        self.value = value  
        self.left = left    
        self.right = right  
        self.code = ''      

I have a list of Node. The question is, how can I extract the node with the lowest self.value attribute?

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
Sergio
  • 81
  • 4

1 Answers1

2

You could use the built-in min function with an anonymous function to access value parameter:

min(listNodes, key=lambda x: x.value)

Or you can define the rich comparison methods __lt__ and __eq__ in Node (you can define additional rich comparison methods, but these two are sufficient for ordering like min):

class Node:def __init__(self, node, value, left=None, right=None):
        self.node = node    
        self.value = value  
        self.left = left    
        self.right = right  
        self.code = '' 
 
    def __iter__(self):
        return self

    def __lt__(self, other):
        return self.value < other.value
    
    def __eq__(self, other):
        return self.value == other.value

which will allow min to directly compare the nodes finding the minimum!

min(listNodes)

Before Python3, it was possible to use the now-deprecated __cmp__ method to create all the rich comparison methods at once; see Question About This and Linked Official Notes

ti7
  • 16,375
  • 6
  • 40
  • 68
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
  • 1
    This assumes that `Node` is iterable... – OneCricketeer Nov 01 '21 at 18:34
  • @OneCricketeer I added the `__iter__` function to the class, but I'm not sure if it can work without it, as all the elements in the list are the same class type and lambda function is getting the value attribute – Cardstdani Nov 01 '21 at 18:43
  • 1
    `return self` doesn't make sense for a `__iter__` definition. Assumably, OP wants `min([self.value, self.left.value, self.right.value])` (recursively) – OneCricketeer Nov 01 '21 at 18:45
  • 1
    note that `cmp` is gone in Python3, so (for this case) `__lt__` and `__eq__` should be defined instead (though practically the signature is the same) see https://stackoverflow.com/questions/22490366/how-to-use-cmp-in-python-3 – ti7 Nov 01 '21 at 18:58