これは解決策であり、アルゴリズムではありません。アルゴリズムはitertools.combinations
の実装に埋め込まれています(ただし、以下を参照)。ライブラリ関数が組み込まれていない実装の場合)。
from functools import reduce
from itertools import combinations
def assign(v, p):
v[p[0]] = p[1]
return v
def interp(word, letter, size):
return (''.join(reduce(assign, zip(comb, word), [letter] * size))
for comb in combinations(range(size), len(word)))
(それらをより見やすくするために、ドットの代わりにスペースを使用)例:
>>> print('\n'.join(interp("cats", ".", 6)))
cats..
cat.s.
cat..s
ca.ts.
ca.t.s
ca..ts
c.ats.
c.at.s
c.a.ts
c..ats
.cats.
.cat.s
.ca.ts
.c.ats
..cats
それはcombinations
を実装するために、実際にはかなり簡単です(それが既に定義されているので、なぜ、わざわざ?)。ここでは効率的にあまりにも多くのタプルの連結を行う一つの解決策だが、アルゴリズムを示しています。つまり
def combs(vec, count, start=0):
if count == 0:
yield()
else:
for i in range(start, len(vec) + 1 - count):
for c in combs(vec, count - 1, i + 1):
yield((i,) + c)
、それぞれの可能な最初の位置のために、それを選択し、残りの位置との組み合わせを完了します。 itertools
モジュールからcombinations
で - あなたは4つの文字が非常に簡単であるべきな組み合わせを作成することができます
def interp(word, letter, size):
if len(word) == 0:
yield letter * size
else:
for i in range(size + 1 - len(word)):
for comb in interp(word[1:], letter, size - i - 1):
yield letter * i + word[0] + comb
これは非常に密集しているので、私はこれをupvoteすることを躊躇していますが、質問は実装を求めていました。 – Blender
@blender:もっと時間があれば分かりやすくなります:) – rici
hm、approximatly 5分間これを見ても、私は同じ回答を投稿したのか、それとも違うのかは分かりません:)しかし、少なくとも同じように見える。 – MSeifert