0
$\begingroup$

My question may be very stupid, and trivial, but looking forward to some suggestions -

As a visualization let's consider a rectangle with four vertices represented by [1,2,3,4]. Now I want to find a triplet of numbers from them like (1, 2, 3).

ly = [1,2,3,4]
triplets = []
for i in ly:
    for j in ly:
        for k in ly:
            triplets.append((i,j,k))

However, I want a combination of those triplets such that (1, 2, 3) is the same as (3, 2, 1), because the angle between these indices is given by 2. I mean I want this triplet occurring only once defined by the middle number. So, in my case, (4, 1, 2) is the same as (2, 1, 4). So I want either (2, 1, 4), or (4, 1, 2), but not both.

Again, to re-paraphrase, I would expect 4 triplets with a distinct number in middle [1,2,3] (or [3,2,1), as I consider [1,2,3] the same as [3,2,1]) then [1,3,2] (or [2,3,1]), then [2,1,3] (or [3,1,2]), and [2,4,3] (or [3,4,2]). So, the first and the last number in the triplet should be distinct.

I hope my question makes sense.

$\endgroup$

1 Answer 1

2
$\begingroup$

If I understand what you want correctly, the middle index can be any one of the vertices, and the order of the first and third number doesn't matter, with repeats allowed? So [1,1,1] is a valid triplet.

You can guarantee uniqueness by first iterating over all 4 possible middle indices, and then only iterate over the other 2 indices such that index 1 is less than or equal to index 3:

    ly = [1,2,3,4]
    triplets = []
    for j in ly:
        for i in ly:
            for k in ly:
                if i <= k:
                    triplets.append((i,j,k))
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.