Project Euler problem 79: deducing a passcode
The thing wrong isn't so much the code as the algorithm. Your approach to finding the next first digit is inefficient. What is the right way to approach this problem? 

This is actually one of the few Euler problems that I've been able to do on paper. Let's start with just establishing the constraints. We know what digits have to go before other digits and thankfully there aren't any repeats. We can turn the input text into a graph, where a directed edge indicates that a digit has to precede another digit. Behold, the power of pictures:



Just looking at the graph makes the answer obvious: 73162890. Why is it obvious and what work did we do in our head to determine this answer? We sorted the graph. Specifically, we performed a topological sort by following the edges. The algorithm is very straightforward assuming no cycles:

L &lt;- Empty list that will contain the sorted nodes
while there are unmarked nodes do
    select an unmarked node n
    visit(n)

function visit(node n)
    if n is not marked then
        for each node m with an edge from n to m do
            visit(m)
        mark n
        add n to the head of L


Since we're dealing with digits, we can keep our edges as just an array of sets:

class DigitGraph(object):
    def __init__(self):
        self.digits = set()
        self.edges = [set() for _ in xrange(10)]

    def add_edge(self, i, j): 
        self.digits.add(i)
        self.digits.add(j)
        self.edges[i].add(j)


And then topo-sort can be written by directly translating the algorithm. I'll leave the rest as an exercise. I time it at about 2x faster.