1

I have a list.

For example: [1, 2, 3, 4]

The result I would like to have is: [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4].

So I would calculate all the possible couple (the order isn't important) with no equal elements. I did this:

result = []
    for first_elem in my_list:
        for second_elem in my_list:
            if first_elem!=second_elem:
                c = [first_elem,second_elem]
                result.append(c)
    return result

Is there a method to do this more efficient(here we have about n^2) without using libraries? Thanks

This didn't answer my question.

edoardottt
  • 100
  • 1
  • 11
  • 4
    You're looking for [`itertools.combinations`](https://docs.python.org/3.8/library/itertools.html#itertools.combinations) – ForceBru Nov 28 '19 at 16:14
  • 2
    "without using libraries" – Sayse Nov 28 '19 at 16:14
  • Why would you *not* use a function in the standard library? Nothing about this question suggests it is a homework assignment. – chepner Nov 28 '19 at 16:15
  • 2
    @Sayse, "without using _external_ libraries". `itertools` is part of the standard library. It's not _external_, it's available in every proper Python setup – ForceBru Nov 28 '19 at 16:15
  • Yes I don't want to use libraries, external or not... – edoardottt Nov 28 '19 at 16:16
  • 2
    @ForceBru - External or not, it seems pretty clear that the OP is looking for a logic based answer as opposed to a single function call – Sayse Nov 28 '19 at 16:16
  • why don't you want to use libraries? – Dan Nov 28 '19 at 16:16
  • 1
    *"here we have about n^3"* - the code in your question is O(n^2), which is asymptotically optimal for generating pairs because there are O(n^2) of them to generate. – kaya3 Nov 28 '19 at 16:17
  • This *isn't* O(n^3); it's O(n^2). Since there are O(n^2) elements in the result, this is (asymptotically) as efficient as it gets. – chepner Nov 28 '19 at 16:18
  • Yes, you're right, originally i did a for loop inside two nested loops, sorry. **Anyway, who marked this as duplicate...look better at the question! That answer isn't answering my problem!** – edoardottt Nov 28 '19 at 16:21
  • 1
    Not really a duplicate since that question was about generating *all* combinations and not just pairs. In any event, the standard way to do this is to use indices with the first index, say `i`, ranging from 1 to `n-1` and the second index, say `j`, ranging from `0` to `i-1`. The loops themselves should be set up so that duplicates don't appear. No point to iterate over all `n^2` ordered pairs of elements and filter them. – John Coleman Nov 28 '19 at 16:22
  • @JohnColeman Thanks a lot. I did this: i from 0 to n-1 and j from i+1 to n – edoardottt Nov 28 '19 at 16:32

0 Answers0