Tuesday, April 30, 2013

Python string permutation

很多時候需要有枚舉一串字的需求

Python 內建的 itertools 其實就有內建了

再加上 generator 語法可以很簡單的解決問題


In [1]: import itertools

In [2]: S = "abc"

In [3]: ("".join(i) for i in (itertools.permutations(sorted(S))))
Out[3]: <generator object <genexpr> at 0x1aa02d0>

In [4]: print ["".join(i) for i in (itertools.permutations(sorted(S)))]
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

In [5]: for i in ("".join(i) for i in (itertools.permutations(sorted(S)))): print i,
abc acb bac bca cab cba



"".join 是常用的 list->string 的標準作法,因為原本拿出來的結果是一個個的 tuple



In [6]: list(i for i in (itertools.permutations(sorted(S))))
Out[6]:
[('a', 'b', 'c'),
 ('a', 'c', 'b'),
 ('b', 'a', 'c'),
 ('b', 'c', 'a'),
 ('c', 'a', 'b'),
 ('c', 'b', 'a')]

No comments:

Post a Comment