Answer the question
In order to leave comments, you need to log in
[[+content_image]]
How to quickly select all combinations from an array (combinatorics)?
Good afternoon! standard task. There is an array [1,2,3] , there is n = 2 . You need to select all combinations from the array by n. That is, they should get: [[1,2], [1,3], [2, 3]] .
You can, of course, loop in a loop, but as the array size and n increase, the calculations will take too long due to the large number (> 66%) of eliminating unnecessary combinations.
So the question is how to implement it correctly?
Answer the question
In order to leave comments, you need to log in
> [(i, j) for i in range(1, 4) for j in range(i + 1, 4)]
[(1, 2), (1, 3), (2, 3)]
comb ∷ Int → [a] → [[a]]
comb 0 _ = [[]] -- из нуля элементов можно составить только пустой список
comb n [] = [] -- из пустого списка нельзя составить ничего
comb n lst = do -- списочная монада, работает как вложенные for
-- tails для [1,2,3] вернёт [[1,2,3], [2,3], [3], []], т.е. все возможные хвосты
-- мы перебираем все хвосты, кроме последнего пустого
-- и дербаним его на голову l и остаток ls
(l:ls) ← filter (not ∘ null) $ tails lst
-- перебираем сочетания из n - 1 элементов от ls
ls' ← comb (n - 1) ls
-- и присобачиваем l к каждому
return (l:ls')
Stop screwing around here.
>>> from itertools import combinations
>>> combinations([1, 2, 3], 2)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question