【问题标题】:ordered word perminuations in pythonpython中的有序单词排列
【发布时间】:2016-09-08 18:13:47
【问题描述】:

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

我的代码:

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@']

【问题讨论】:

  • 请在问题中包含您的代码作为文本。例如,我的防火墙阻止我查看您的链接。

标签: python data-generation


【解决方案1】:

在您的情况下,您可以使用 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 字符数不同。

【讨论】:

  • 这很好,如果你能用几句话解释它是如何工作的,那就更好了。
猜你喜欢
  • 2021-01-11
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2019-03-24
相关资源
最近更新 更多