I am a novice student in Python (and programming in general).
I am supposed to make a python program that opens two files with random numbers in them and creates a new file with the numbers ordered from lowest to highest.
So I made this code that iterates using two for loops through all the numbers, searching for the lowest, very basic stuff, than stores the number and its position, appends to a Lmix list that will be saved on the final file and stores the numbers position to delete it from that list so it won't be found again.
The variables are in Portuguese, but I translated them in the comments, the rest are self-explanatory.
arq1 = open("nums1.txt","r") arq2 = open("nums2.txt","r") arqmix = open("numsord.txt","w") L1 = arq1.readlines() L2 = arq2.readlines() Lmix =  L1 = list(map(int,L1)) # converts lists into int L2 = list(map(int,L2)) cont = 0 menor = L1 # "Menor" is the variable that stores the lowest number it finds menorpos = 0 # "Menorpos" is the position of that variable in the list, so it can delete later listdec = 0 # "listdec" just stores which list the number was from to delete. while cont != (len(L1)+len(L2)): # while loops that finds the lowest number, stores the number and position, appends to the Lmix and deletes from the list so it won't be found on next iteration n = 0 for n,x in enumarate(L1): m = 0 for m,y in enumarate(L2): if x<menor: menor = x menorpos = n listdec = 0 elif y<menor: menor = y menorpos = m listdec = 1 m += 1 n += 1 Lmix.append(menor) if listdec == 0: del L1[menorpos] elif listdec == 1: del L2[menorpos] cont += 1 for x in Lmix: arqmix.write("%d\n"%x) arq1.close() arq2.close() arqmix.close()
But everytime I run it, this error appears:
Traceback (most recent call last): File "C:/Users/Danzmann-Notebook/PycharmProjects/untitled/aula18.py", line 41, in del L2[menorpos] IndexError: list assignment index out of range
I know what it means but I just can't understand why it happens, and how can I solve it.
Any help would be appreciated.
Thanks in advance, sorry for any grammar error, english is not my native language.