Search code examples
pythonlistlist-comprehension

My answer is not running for one of the sample


I wrote this python3 code using list comprehensions, my code is running fine for one of the samples, but showing one extra list in the answer as it can be seen in the picture attached. It's showing [1,1,0] in the answer when it's not supposed to.

I changed the ranges, and even changing the == sign to != and changing remove to append but then it shows some other error.

QUESTION:

Print an array of the elements that do not sum to n Input Format Four integers x, y, z and n, each on a separate line. Constraints Print the list in lexicographic increasing order.

CODE:

if __name__ == '__main__':
a = int(input())
b = int(input())
c = int(input())
n = int(input())
list1=[[x,y,z] for x in range(a+1) for y in range(b+1) for z in range(c+1)]
for i in list1:
    if sum(i)== n:
        list1.remove(i)
print(list1)

SAMPLE:

Input: 1 1 1 2

My Output: [[0, 0, 0], [0, 1, 0], [1, 0, 0]]

Expected Output: [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]


Solution

  • Is this what you are looking for?

    a = int(input())
    b = int(input())
    c = int(input())
    n = int(input())
    
    l = [[x,y,z] for x in range(a+1) for y in range(b+1) for z in range(c+1) if (x+y+z) != n]
    print(l)