list out of range when going through an array checking for duplicates in python 2.7

72 views Asked by At

The goal is simple: there is a file with x numbers separated by ` . If there are dublicates of the number in the file they should be deleted. I decided to solve this by comparing the n member with all others from n to len(array). The code:

    #deletes repeated numbers separated by `
questioned=open("key_file.txt",'r+')
numbers=questioned.read()
#print(numbers)
numb=[]
number=[]
for each in numbers:
    if each=='`':
        number.append(''.join(numb))
        numb=[]
    else:
        numb.append(each)
i,j=0,0
for i in xrange(len(number)): #we don't need to compare last number
    for j in xrange(i+1,len(number)-1):#don't need to compare to itself
        #print(len(number)," ",i," ",j)
        if number[i]==number[j]:
             number.pop(j) #tried del number[j]


questioned.close()

However, it seems that I manage to get out of range during the process even though I specified that xrange should go to len(array). My guess is the len(number) is not being continually reassessed leading to the number being out of range because a bunch of numbers got deleted? Any pointers/tips would be great. Thanks a lot for your time!

1

There are 1 answers

0
Sleepycoder On

Alright, it seems like my fears were correct. In the 2nd loop j manages to go over len(number) which leads to the error...

#deletes repeated numbers separated by `
questioned=open("key_file.txt",'r+')
numbers=questioned.read()
#print(numbers)
numb=[]
number=[]
for each in numbers:
    if each=='`':
        number.append(''.join(numb))
        numb=[]
    else:
        numb.append(each)
i,j=0,0
def compare(number,i,j):
    if number[i]==number[j]:
        number.pop(j)
        compare(number,i,j)
    return number

for i in xrange(len(number)):
    for j in xrange(i+1,len(number)-1):
        if j>len(number)-1: 
            break
        #print(len(number)," ",i," ",j)
        #try:
            compare(number,i,j)

        #except: print('i,j',i,' ',j,'len ',len(number))

questioned.close()

Works fine without try statement. I am not sure why this happens but it does seem to be the case. If you guys have an explanation that would be great :/