2
#function description   
 def getMoneySpent(keyboards, drives, b):
        q = []
        for i in range(len(keyboards)):
            for j in range(len(drives)):
                q.append(keyboards[i] + drives[j]) 
        for m in range(len(q)):
            if(q[m] > b):
                q.remove(q[m])
            else:
                pass
        if q is not None:
            return max(q)
        else:
            return -1

And the error message is :

Traceback (most recent call last):
    File "Solution.py", line 42, in <module>
        moneySpent = getMoneySpent(keyboards, drives, b)
    File "Solution.py", line 15, in getMoneySpent
        if(q[m] > b):
    IndexError: list index out of range

keeps on getting this error message.This is a problem in hackerrank i will link that below for anybody who wants further reference:

https://www.hackerrank.com/challenges/electronics-shop/problem

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • 3
    Does this answer your question? [python : list index out of range error](https://stackoverflow.com/questions/1798796/python-list-index-out-of-range-error) – Hampus Larsson May 19 '20 at 07:26

2 Answers2

3

The problem is q.remove(q[m]), you are removing items from a list while you are iterating over it.

one solution is you save all desired ms to be removed in another list and delete them after the loop finished.

or

You can look at these links to get better clue:

How to delete list items while iterating

Another link

You can understand this:

q[:] = [i for i in q if i <= b]

put this line instead of your for loop over q.

Also note that:

else:
    pass

is redundant, you can remove.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

You may try this instead:

def getMoneySpent(keyboards, drives, b):
    q = []
    for k in keyboards :
        for d in drives :
            price = k + d
            if price <= b :
                q.append(price) 

    return max(q) if q else -1

Instead of removing elements, just don't add them in the first place...

lenik
  • 23,228
  • 4
  • 34
  • 43