0

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)
ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
  • print out `newS` before the for loop. I'm guessing it's less than 2 elements big. – Mateen Ulhaq Jun 27 '18 at 05:27
  • Possible duplicate of [IndexError: list index out of range and python](https://stackoverflow.com/questions/1098643/indexerror-list-index-out-of-range-and-python) – Sayse Jun 27 '18 at 05:27
  • when `i=0, k=1` ; when `i = last element, k =last element +1` , so k is out of range. just do a minus 1 from your iterator `range(len(newS) - 1)` . assuming everything else is correct, should work fine – pyeR_biz Jun 27 '18 at 05:36
  • or you could just initialize `k=0` – Raghav Patnecha Jun 27 '18 at 05:38

2 Answers2

0

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).

dpattayath
  • 160
  • 5
0

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

Hamid Mir
  • 363
  • 1
  • 9