1

can someone please help me why i am getting out of index error.

def subset(lst,n):
A = 0
B = 1
C = 2
for i in range(len(lst)):
    if n == lst[A]+lst[B]+lst[C]:
        return ('True')
    if n != lst[A]+lst[B]+lst[C]:
        C = C+1

i am getting below output.

subset([1,2,5,3],6)
Out[136]: 'True'
subset([1,2,5,3],9)
if n == lst[A]+lst[B]+lst[C]:

IndexError: list index out of range

I need to pass the list and add three numbers and check and see if its equal to n.

1
  • Do accept an answer if it feels that it has answered your problem Commented Oct 12, 2015 at 18:56

3 Answers 3

1

You're not using i but adding up C, which causes the error. Maybe the following is what you want:

def subset(lst,n):
    for A in range(len(lst)-2):
        for B in range(A+1, len(lst)-1):
            for C in range(B+1, len(lst)):
                if n == lst[A]+lst[B]+lst[C]:
                    return ('True')
    return('False')
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, thats what i was trying to get. If you don't mind i have one qq(i am new to python, this might be stupid question :( .....) After you do the for A in range will it go to the if n == part or will it go to for B in range.
It will go to for B in range part. They are called nested loops. For a certain A, B changes in range. The same is true for C. For certain A and B, C changes in range. Sorry for an extremely late reply!
0

Your line

if n != lst[A]+lst[B]+lst[C]:
        C = C+1

is allowing C to grow. There are a ton of circumstances in which this code will fail for the same reason, but there are specific inputs that will not cause this to fail so it won't always do so. You need to make sure C never gets larger than your list length - 1

I'm not entirely sure what you're trying to do, so this is just the direct answer to why you're getting the out of index error.

Comments

0

C = C+1 eventually becomes 4, but the last index of [1,2,5,3] is 3. that is why in line n == lst[A]+lst[B]+lst[C] it fails

You may want to change you loop to:

 for i in range(len(lst)):
        if n == lst[A]+lst[B]+lst[C]:
            return True
        elif C < len(lst) -1:
            C += 1
       else:
            return False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.