Hello Everyone,

I have a list of digits. What is the most efficient way to count the number of tokens between two known digits?

Here is what I came up with:

def dis(l, a1, a2):
    i1 = l.index(a1)
    i2 = l.index(a2)
    distance = i2 - i1 - 1
    return distance

E.g. l = [1, 2, 3, 4, 5]
>>> print dis(l, 1, 5)
3
>>> print dis(l, 1, 3)
1
>>> print dis(l, 3, 4)
0

Is there a better (=faster) way of doing this?

Thank you,
m.

How about

seq[seq.index(first):].index(second)

Here more final version from the idea I threw without testing possibility:

>>> seq
[1, 2, 3, 4, 5, 2]
>>> def dis(seq, first,second):
    return seq[seq.index(first):].index(second)-1

>>> dis(seq,2,2)
-1
>>> def dis(seq, first,second):
    return seq[seq.index(first)+1:].index(second)
>>> dis(seq,2,2)
3

>>>

So the better form is:

def dis(seq, first,second):
    return seq[seq.index(first)+1:].index(second
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.