ordered word perminuations in python
<p>So my question is simple, and half of it is already working.
I need help with generating ordered word-permutations. </p>

<p>My code:</p>

<pre><code>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')
</code></pre>

<p>My current code does half of the job, but I've reached a "writer's block"</p>

<pre><code>&gt;&gt;&gt;deform({'a':'@'}).first_iter('aaa')

['@aa', 'a@a', 'aa@']
</code></pre>

<p>Here's the results from my currently made script. </p>

<p>What code is supposed to do is - take the word, and reorder it with other characters in the replacement. I've successfully made it do it with one character, but I need help with making all the results. For example:</p>

<pre><code>['@aa', 'a@a', 'aa@', '@@a', 'a@@', '@a@']
</code></pre>

<p>In your case you can use <code>permutations</code> function which could return all possible orderings, no repeated elements.</p>

<pre><code>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
</code></pre>

<p>I divided it into two collections because they differ number of <code>@</code> and <code>a</code> characters.</p>

python data-generation