-1

所以我的问题很简单,其中一半已经在起作用。我需要帮助来生成有序的单词排列。

我的代码:

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', 'a@a', 'aa@']

这是我当前制作的脚本的结果。

代码应该做的是 - 取出单词,并用替换中的其他字符重新排序。我已经成功地用一个角色做到了,但我需要帮助才能做出所有的结果。例如:

['@aa', 'a@a', 'aa@', '@@a', 'a@@', '@a@']
4

1 回答 1

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字符不同。

于 2016-09-08T18:14:46.040 回答