Python Forum
Check if a list exists in given list of lists - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Check if a list exists in given list of lists (/thread-25643.html)



Check if a list exists in given list of lists - Daniel94 - Apr-06-2020

I want to check if a list of tuples contains a specific tuple. If
numbers = [('a','a'), ('c','a')]
look = ('a','c')
"look" should not be contained in "numbers". But that's how my code thinks right now.
  def find_edge(self, src, dst):
        """
        Returns True if there's an edge from node `src` to node `dst`.
        """
        # Check if nodes exist
        if self.find_node(src) is True and self.find_node(dst) is True:
            src_node = self.return_head(src)

            src_edges = src_node.list_edges()
            src_edges_weightless = [x[:-1] for x in src_edges]

            possible_edge = (src, dst)

            for elem in src_edges_weightless:
                if collections.Counter(elem) == collections.Counter(possible_edge):
                    return True

        return False
[Image: 6DHp5pg.jpg]

So when looking if ("a","c") is contained in the list, return should be FALSE. However right now it returns TRUE. Any ideas why?


RE: Check if a list exists in given list of lists - Daniel94 - Apr-06-2020

Solved it by adding changing to this:

            for elem in src_edges_weightless:
                if collections.Counter(elem) == collections.Counter(possible_edge):
                    if elem[0] == possible_edge[0] and elem[1] == possible_edge[1]:
                        return True



RE: Check if a list exists in given list of lists - deanhystad - Apr-07-2020

This is why your original program did not work:
import collection
x = collections.Counter(['a', 'b'])
y = collections.Counter(['b', 'a'])
print(x)
print(y)
print(x==y)
Output:
Counter({'a': 1, 'b': 1}) Counter({'b': 1, 'a': 1}) True
Counter does not care about order of entries in the source collection.

This is what your function does with all the extra stuff removed:
numbers = [('a','a'), ('c','a')]

def find_edge(nodes, x, y):
    for node in nodes:
        if x == node[0] and y == node[1]:
            return True
    return False

print(find_edge(numbers, 'a', 'c'))
print(find_edge(numbers, 'c', 'a'))
Output:
False True