0

When we input x = 1, y = 1, z = 1 and n = 2, there's one result that shouldn't be printed but it doesn't happen.

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 1, 1]] <- last result

x = int(input())
y = int(input())
z = int(input())
n = int(input())

list1 = [ 
    [i,j,k] 
    for i in range(x+1)
    for j in range(y+1)
    for k in range(z+1)
]

list1.sort()
print(list1)

for subList in list1:
    if sum(subList) == n:
        list1.remove(subList)

it shouldn't print the sublist = [1,1,0], the sum is 2, despite my command: if sum(subList) == n:

What should I do?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    Removing elements from a list while looping over it is generally a bad idea. – TimbowSix Jan 14 '23 at 21:16
  • To be clear, your goal is to end up with a list of lists where the sub lists that add up to n have been filtered out? – rhurwitz Jan 14 '23 at 21:20
  • @rhurwitz you're right, that was my purpose – Caio Alves Jan 14 '23 at 21:43
  • Hard to get the formatting right in a comment, but if you put this line at the end of your `list1` list comprehension it should keep out the sub lists that sum to n: `if i + j + k != n` – rhurwitz Jan 14 '23 at 21:48
  • @rhurwitz thank you! it's worked. I understood my mistake, when the program removed an element (sublist), its index had changed, so, it wasn't interated in the execution. – Caio Alves Jan 14 '23 at 21:56

0 Answers0