Search code examples
pythonlistnodes

Better way compare nodes in a list


Noob, trying to add 'unique' Nodes to a list, i.e. with my simple code, I only want the 2 unique nodes, not any duplicate entries. I found a poor workaround, where I created a temp list, added the values (as list items, not as nodes) to the temp list if unique, and then added all items from temp to my list of Nodes (converting them to Nodes at that point), but I'm sure there's a better much cleaner way to do this.

class Node():
    # current actor, source, movie
    def __init__(self, state, parent, action):
        self.state = state
        self.parent = parent
        self.action = action

x = Node(5,4,3)
y = Node(5,4,2)
z = Node(5,4,3)

listz = []

if x not in listz:
    listz.append(x)

if y not in listz:
    listz.append(y)

if z not in listz:
    listz.append(z)

for item in listz:
    print(item.state, item.parent, item.action)

Current Outputs (incorrect):
5 4 3
5 4 2 
5 4 3

Should Output (correct):
5 4 3
5 4 2 

Simple solutions I can follow and implement are preferred to clever ones I can't.


Solution

  • you can declare a eq() method in your Node class to easily compare nodes with each in a way you want.

    What this does is that everytime you insert a node and call the Not in method, it calls this __eq__ method instead of the default way to compare nodes, and hence is able to detect similar Nodes. What was happening to your original code was that the Not in was just comparing the memory location of all nodes (which are always different)

    For example,

    class Node():
        # current actor, source, movie
        def __init__(self, state, parent, action):
            self.state = state
            self.parent = parent
            self.action = action
        def __eq__(self, b):
            return (self.state == b.state) and (self.parent == b.parent) and (self.action == b.action)
    
    x = Node(5,4,3)
    y = Node(5,4,2)
    z = Node(5,4,3)
    
    listz = []
    
    if x not in listz:
        listz.append(x)
    
    if y not in listz:
        listz.append(y)
    
    if z not in listz:
        listz.append(z)
    
    for item in listz:
        print(item.state, item.parent, item.action)