【Python Ruby】組み合わせ
最近、暇な時にアルゴリズムの本( プログラマ脳を鍛える数学パズル) 読んでいます。 その際、順列(組合わせ)のメソッドがあることを知りました。 以下備忘録として書いておきます。
Ruby
RubyではArrayクラスのcombinationメソッドが 使えるようです。
ary = ['1', '2', '3', '4'] # 組み合わせの重複なし:1,2,3,4の中から2つの数字を選ぶ ary.combination(2).to_a # 戻り値 [["1", "2"], ["1", "3"], ["1", "4"], ["2", "3"], ["2", "4"], ["3", "4"]] # 順序の重複なし ary.permutation(2).to_a # 戻り値 [["1", "2"], ["1", "3"], ["1", "4"], ["2", "1"], ["2", "3"], ["2", "4"], ["3", "1"], ["3", "2"], ["3", "4"], ["4", "1"], ["4", "2"], ["4", "3"]]
Python
Python では itertoolsモジュールのcombinationsメソッドが 使えるようです。
import itertools ary = ['1', '2', '3', '4'] combinations = itertools.combinations(ary, 2) print(list(combinations)) # [('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')] permutations = itertools.permutations(ary, 2) print(list(permutations)) # [('1', '2'), ('1', '3'), ('1', '4'), ('2', '1'), ('2', '3'), ('2', '4'), ('3', '1'), ('3', '2'), ('3', '4'), ('4', '1'), ('4', '2'), ('4', '3')]
参考
permutation (Array) - Rubyリファレンス
10.1. itertools — 効率的なループ実行のためのイテレータ生成関数 — Python 3.6.5 ドキュメント