fc2ブログ
組み合わせと順列
以前こんな記事を書いていましたが、Pythonで組み合わせと順列の処理をするには、標準のitertoolsが便利です。必要なときにいつもモジュールの名前が分からなくなるので、こうして書いて覚えよう作戦です。

>>> import itertools
>>> for c in itertools.combination([1,2,3,4,5],2):
... print(c)
...
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'module' object has no attribute 'combination'
>>> for c in itertools.combinations([1,2,3,4,5],2):
... print(c)
...
(1, 2)
(1, 3)
(1, 4)
(1, 5)
(2, 3)
(2, 4)
(2, 5)
(3, 4)
(3, 5)
(4, 5)
>>>

itertools.combinationsです。combinationでは無いので注意しましょう。
組み合わせを生成するアルゴリズムの実装は結構頭を使うのでよい練習になるのではないかと思います。とかいいながら、モジュール使ってしまうのですが。
スポンサーサイト



テーマ:プログラミング - ジャンル:コンピュータ

【2010/03/10 17:53】 | Python | トラックバック(0) | コメント(2) | page top↑
| ホーム |