Я просматривал свои лекционные заметки и переделывал пример, который профессор делал в классе. Но я продолжаю получать список ошибок индекса. Любая помощь или объяснение было бы здорово. Я попытался прочитать об этом, но не понял этого, поэтому размещаю его здесь, надеясь, что кто-то сможет мне это объяснить.
Вот что я сделал:
def sortList(list1):
sorted = []
while len(list1)> 0:
lowest = list1[0]
for value in list1:
#we need to place the items in order so first we will find the lowest value
if value < lowest:
lowest = value
#lowest is the smallest number in list1
# now we can add it to the sorted list
sorted.append(lowest)
#we can remove the item from list one
list1.remove(lowest)
return sorted
def median(list1):
list1 = sortList(list1)
#list one is now in sorted order
while len(list1)> 2: # we are trying to take out all the numbers till 2 left (if 3 left it will execute and leave 1)
list1.pop(0) #takes out the first item in the list
list1.pop() #takes out the last item in the list
if len(list1) == 1: # if there is only one item we return it
return list1[0]
else: #returns the avg of those
return((list1[0] + list1[1])/2)
x = [45, -1, 0, 54, 101, 2, 7,11]
print(sortList(x))
print(median(x))
Однако, когда я делаю
print(sortList([45, -1, 0, 54, 101, 2, 7,11]))
print(median([45, -1, 0, 54, 101, 2, 7,11]))
распечатывается нормально. Это почему?
Это ошибка, которую я получаю:
print (медиана (x)) ... return ((list1 [0] + list1 [1]) / 2)
IndexError: список индексов вне диапазона.