简体   繁体   中英

List index out of range Error python

Okay I am getting this error:

File "cows.py", line 34, in <module>
  if newS[i] <= newS[k]:
IndexError: list index out of range

This is my code, Can somebody please help me fix this problem?

speed = []
pos = []
while True:
    try:
        print("Enter cow speed and then position: ")
        a = int(input("Enter position: "))
        b = int(input("Enter speed: "))
        pos.append(a)
        speed.append(b)
        print("Do you want another cow? ")
        c = input("Enter 'no' to stop or any other string to have another cow: ")
        if c == 'no':
            break
        else:
            continue
    except ValueError:
        print("Please enter 1 number only.")
        continue
newP = []
newS = []
while pos:
    mini = pos[0]  # arbitrary number in list 
    for x in pos: 
        if x < mini:
            mini = x
    r = pos.index(mini)
    newS.append(speed.pop(r))
    newP.append(mini)
    pos.remove(mini)    
newS = newS[::-1]
groups = 1
k = 1
for i in range(len(newS)):
    if newS[i] <= newS[k]:
        newS[k] = newS[i]
        k += 1
    else:
        k += 1
        groups += 1
print(groups)

Python array is indexed from 0 and thereby for a list of 5 elements, the iterations will be from 0-4. "range" function generates iterator with elements inclusive of the upper limit, so for if you pass 5 to range, it will generate iterator for 0-5 which will be index out of bound for a 5 element array.

Try changing argument of range function from range(len(newS)) to range(len(newS) - 1).

I entered only 1 speed and position so length of newS will be 1 thus line 32 : k = 1

sets the list index to 1 which is higher than list limits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM