0

Assume I have a set:

s = {1,2,3,4,5}

And now I want to perform an operation of every possible unordered pair of that set, say addition. For a list I would do:

for i in range(len(s)):
    for j in range(i+1,len(s)):
        print(s[i]+s[j]

But for a set the best I could come up with is:

for idx, val in enumerate(s):
    for idx2, val2 in enumerate(s):
        if idx2<=idx:
           continue
        print(val+val2)

Which does not seem satisfactory to me: One because the code has a higher complexity and also because it is less clear. What would be a pythonic (and fast) way to do this?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 3
    The `itertools` solution shown in the duplicate will work for any iterable, including `set`s – Patrick Haugh Jan 23 '20 at 20:43
  • `set` is not ordered. Therefore "every possible unordered pair of that set" is every pair. – deadvoid Jan 23 '20 at 20:44
  • 2
    @deadvoid: "Unordered" in this case means that pairing from `{'a', 'b'}` (for the simple example) should produce *either* `('a', 'b')` *or* `('b', 'a')`, but not both. The lack of ordering for `set`s means you don't know which of those two `tuple`s would be produced, but the OP wants to make sure they only get one of them. `itertools.combinations` will do that for them (with roughly the same algorithm as their first example, preconverting to a `tuple` under the hood so indexing works), just more efficiently. – ShadowRanger Jan 23 '20 at 21:09
  • 1
    Hmm, I think it confused me before, that wording, I kind of remember now I made the same assumption about it in the past. The thing is I rarely use itertools combination so since `{a, b}` == `{b, a}` for `set`, my mind made a mental jump, while it didn't occur to me the distinction between pairs was really eventually for tuple pairs `(a, b) != (b, a)`. Anyway, thank you for taking the time @ShadowRanger, cheers. – deadvoid Jan 23 '20 at 21:22

0 Answers0