S
sam
hey everybody, this is my first time posting here. i'm pretty new to
python and programming in general (as you'll soon work out for
yourselves...)
i'm trying to code a version of a selection sort and the heart of the
code is as follows (no_lines is simply the number of items to be
sorted, read out of an input file):
for j in range(0, no_lines):
k = 0
while k < no_lines:
sorted_check = 0
if list_initial[k] < list_initial[k+1]:
temp_str = list_initial[k]
elif list_initial[k] == list_initial[k+1]:
temp_str = list_initial[k]
elif list_initial[k] > list_initial[k+1]:
temp_str = list_initial[k+1]
sorted_check = 1
k += 1
list_initial.remove(temp_str)
list_final.append(temp_str)
no_lines -= 1
if sorted_check == 0:
break
problem is, i keep getting a "list index out of range" error. i've had
this problem before in different contexts with lists in loops.
i thought i had it cracked when it occurred to me that i needed to
decrement no_lines to take into account that list_initial was shrinking
as i deleted sorted items, but i still got the same error. it's
probably something trivial, but i can't seem to get round it by using
while loops, and i had the same problem with cmp(), hence the explicit
comparison above, which still doesn't work. can anyone help a beginner
out with this?
many thanks in advance,
sam lynas
python and programming in general (as you'll soon work out for
yourselves...)
i'm trying to code a version of a selection sort and the heart of the
code is as follows (no_lines is simply the number of items to be
sorted, read out of an input file):
for j in range(0, no_lines):
k = 0
while k < no_lines:
sorted_check = 0
if list_initial[k] < list_initial[k+1]:
temp_str = list_initial[k]
elif list_initial[k] == list_initial[k+1]:
temp_str = list_initial[k]
elif list_initial[k] > list_initial[k+1]:
temp_str = list_initial[k+1]
sorted_check = 1
k += 1
list_initial.remove(temp_str)
list_final.append(temp_str)
no_lines -= 1
if sorted_check == 0:
break
problem is, i keep getting a "list index out of range" error. i've had
this problem before in different contexts with lists in loops.
i thought i had it cracked when it occurred to me that i needed to
decrement no_lines to take into account that list_initial was shrinking
as i deleted sorted items, but i still got the same error. it's
probably something trivial, but i can't seem to get round it by using
while loops, and i had the same problem with cmp(), hence the explicit
comparison above, which still doesn't work. can anyone help a beginner
out with this?
many thanks in advance,
sam lynas