Alexis
Alexis

Reputation: 120

sort() doesn't work with list comprehension

i am trying to get a couple of values; that couple is formed by i and j ; the addition between them could be N or N+1 . i want a list with the numbers that satisfy the condition. for example if N=3 then i need an output like this:

>>> [ [1,2], [2,2]  ]

my code so far is:

N = 3
answer = []
answer = [(i,j) for i in range (1,N) for j in range(1,N) if [i,j].sort() not in answer and i+j == N or i+j == N+1 ]
print(answer)

but when i run this, i receive this output:

>>> [ [1,2] , [2,1], [2,2] ]

where the nested list (couple) [2,1] is a repetead element. why sort is not working in this code?

Upvotes: 1

Views: 1308

Answers (1)

akuiper
akuiper

Reputation: 214957

The inplace .sort() method is one problem, but the answer is empty list, and it's not updated in the list comprehension until it finishes, so probably you also have to use a regular for loop and if you don't want to check if elements are already in answer, use a set:

answer = set()
values = set([N, N+1])
for i in range(1,N):
    for j in range(1,N):
        if i + j in values:
            answer.add(tuple(sorted((i, j))))

answer
# {(1, 2), (2, 2)}

Upvotes: 4

Related Questions