954,557 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Counting nr of elements between two given strings in a list

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.

Malinka
Newbie Poster
7 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

How about

seq[seq.index(first):].index(second)
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

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
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: