0

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]]

Kashvi
  • 13
  • 5
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – slothrop Aug 22 '23 at 18:27

2 Answers2

0

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)
Galo Torres Sevilla
  • 1,540
  • 2
  • 8
  • 15
0

Just to answer you question, I would use another list comprehension:

list2 = [s for s in list1 if not sum(s) == n]

And now list2 contains all the files you want:

>> ./testnum.py 
1
1
1
2
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
New stuff
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
Xinthral
  • 438
  • 2
  • 10