Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to find the maximum distance between two occurrences of same number in list with Python

1 Answer

0 votes
import math

def GetMaxDistance(lst):
    dic =  dict()
    maximumDistance = 0
    size = len(lst)
    i = 0
    while (i < size) :
        if (not (lst[i] in dic.keys())) :
            dic[lst[i]] = i
            print("dic[lst[i]]=" + str(dic.get(lst[i])), end ="")
            print(" lst[i]=" + str(lst[i]), end ="")
            print(" i=" + str(i))
        else :
            maximumDistance = max(maximumDistance, i - dic.get(lst[i]))
            print("dic[lst[i]]=" + str(dic.get(lst[i])), end ="")
            print(" i - dic[lst[i]]=" + str((i - dic.get(lst[i]))), end ="")
            print(" i=" + str(i))
        i += 1
    return maximumDistance

lst = [7, 1, 4, 3, 1, 5, 3, 4, 9, 1, 3]
        
print(GetMaxDistance(lst))
    


'''
run:

dic[lst[i]]=0 lst[i]=7 i=0
dic[lst[i]]=1 lst[i]=1 i=1
dic[lst[i]]=2 lst[i]=4 i=2
dic[lst[i]]=3 lst[i]=3 i=3
dic[lst[i]]=1 i - dic[lst[i]]=3 i=4
dic[lst[i]]=5 lst[i]=5 i=5
dic[lst[i]]=3 i - dic[lst[i]]=3 i=6
dic[lst[i]]=2 i - dic[lst[i]]=5 i=7
dic[lst[i]]=8 lst[i]=9 i=8
dic[lst[i]]=1 i - dic[lst[i]]=8 i=9
dic[lst[i]]=3 i - dic[lst[i]]=7 i=10
8

'''

 



answered Dec 17, 2022 by avibootz
...