LoginSignup
2
2

More than 5 years have passed since last update.

[python] 同じ要素を考慮した順列の生成

Posted at

同じ要素を含む順列の生成

itertools.permutationsだと、同じ要素のとき、余分に生成される。
同じ数字、同じ文字、同順、等扱うとき使います。
前にジェネレータの使い方で紹介したが、自分が探しにくかったので単体で紹介。
github source: permutation.py

permutation.py
def permutations(iterable, permutation=[]):
    if not iterable: 
        yield permutation
        pass
    for i in [iterable.index(i) for i in set(iterable)]:
        yield from permutations(iterable[:i] + iterable[i+1:], permutation + [iterable[i]])

yield from は再帰的?に、yieldを遠くから返してくれます。
毎回setして、同じ要素の重複を防いでいます。

スライスでくっつけるの若干遅そうなので、うまいやり方あれば教えて欲しいです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2