Reputation: 109
How to find the maximum distance between two same elements/integers of a list in python.
e.g. if a list is [1,3,3,5,6,4,8,6,0,3,5]
Output would be 8
(distance b/w 3's is maximum here)
Upvotes: 3
Views: 378
Reputation: 9806
Using numpy (slower than abc's solution):
import numpy as np
L = [1,3,3,5,6,4,8,6,0,3,5]
x, y = np.meshgrid(L, L)
w = np.where(x == y)
max_dist = np.max(w[1] - w[0])
Upvotes: 0
Reputation: 11939
You can use a dictionary where for each value you save the indices.
from collections import defaultdict
d = defaultdict(list)
for i,el in enumerate(l):
d[el].append(i)
max_dist = max(d[k][-1]-d[k][0] for k in d)
Upvotes: 3