2016-09-08 6 views
-1

私の質問は単純で、その半分はすでに動作しています。 私は順序付けられた単語順列を生成するのに助けが必要です。Pythonで単語の末尾を指定しました

マイコード:

from os.path import isfile 
from string import printable 

def loadRuleSet(fileLocation): 
    rules = {} 
    assert isfile(fileLocation) 
    for x in open(fileLocation).read().split('\n'): 
     if not len(x) == 0: 
      data = x.split(':') 
      if not len(data[0]) == 0 or not len(data[1]) == 0: 
       rules[data[0]] = data[1] 
    return rules 

class deform: 
    def __init__(self, ruleSet): 
     assert type(ruleSet) == dict 
     self.ruleSet = ruleSet 

    def walker(self, string): 
     spot = [] 
     cnt = 0 
     for x in string: 
      spot.append((x, cnt)) 
      cnt += 1 
     return spot 


    def replace_exact(self, word, position, new): 
     cnt = 0 
     newword = '' 
     for x in word: 
      if cnt == position: 
       newword += new 
      else: 
       newword += x 
      cnt+= 1 
     return newword 


    def first_iter(self, word): 
     data = [] 
     pos = self.walker(word) 
     for x in pos: 
      if x[0] in self.ruleSet: 
       for y in self.ruleSet[x[0]]: 
        data.append(self.replace_exact(word, x[1], y)) 
     return data 

print deform({'a':'@A'}).first_iter('abac') 

私の現在のコードは、ジョブの半分を行いますが、私は

>>>deform({'a':'@'}).first_iter('aaa') 

['@aa', '[email protected]', '[email protected]'] 

を「作家のブロック」に達しました。ここに私は現在作られたスクリプトからの結果です。

どのようなコードを実行する必要がありますか?言葉を取り、交換先の他の文字と並べ替えます。私は正常にそれを1人のキャラクターとするようにしましたが、すべての結果を作るのに助けが必要です。例えば:あなたのケースでは

['@aa', '[email protected]', '[email protected]', '@@a', '[email protected]@', '@[email protected]'] 
+3

質問にあなたのコードをテキストとして含めてください。たとえば、私のファイアウォールで私のリンクが見えなくなってしまいます。 –

答えて

2

あなたはすべての可能な順序付けのない繰り返しの要素を返すことができpermutations機能を使用することができます。

from itertools import permutations 
from operator import itemgetter 

perm_one = sorted(set([''.join(x) for x in permutations('@aa')])) 
perm_two = sorted(set([''.join(x) for x in permutations('@@a')]), key=itemgetter(1)) 
print perm_one + perm_two 

彼らは@a文字の数を異なるので、私は2つのコレクションにそれを分けます。

+0

これはどのように動作するかを説明する文章が少ない場合には、これは良いことです。 – kosa

関連する問題