【问题标题】:Algorithm for all permutations of a string in C++ or PythonC++ 或 Python 中字符串的所有排列的算法
【发布时间】:2015-03-19 10:16:02
【问题描述】:

我需要用 c++ 或 python 编写一个函数,它获取一个字符串并打印所有可以加扰的选项。例如 - scramble("abc") 将打印 -

abc
acb
bac
bca
cab
cba

当然不仅仅是长度为3的单词。

【问题讨论】:

    标签: python c++ function recursion scramble


    【解决方案1】:

    在 Python 中,您可以使用 itertools 中方便的排列函数。

    from itertools import permutations
    
    def scrambles(word):
        return [''.join(permutation) for permutation in permutations(word)]
    

    或者,这里有一个明确说明的递归置换算法:

    def permutations(word):
    
        if len(word) == 1:
            # the word is one letter long, so this is the base case; there is only one permutation
            return [word]
    
        # recursively get all permutations of the word after its first letter
        subword_perms = permutations(word[1:])
    
        # insert the first letter at all possible positions in each of the possible permutations of the rest of the letters
        first_letter = word[0]
        perms = []
        for subword_perm in subword_perms:
            for i in range(len(subword_perm)+1):
                perm = subword_perm[:i] + first_letter + subword_perm[i:]
    
                # test to make sure permutation wasn't already found (which is possible if some letters are duplicated within the word)
                if perm not in perms:
                    perms.append(perm)
        return perms
    

    【讨论】:

    • 太棒了!但它是如何工作的?这是python中的一个很好的技巧,但我需要知道算法是如何工作的。有人可以尝试用 C++ 编写吗?
    【解决方案2】:

    这是一个较短的递归函数,用于查找字符串中字母的所有排列:

    def gen_perms(n,text):
        if n == 1:
            return {a for a in text}
        temp = {a + b
               for a in text
               for b in gen_perms(n-1,text)}
        return temp
    

    n 是您要生成的单词/集合的长度

    text 是您要使用的一组字母。

    我使用集合是因为​​它们没有重复的条目;只有独特的元素。

    为了解释算法,从 n=1 的基本情况开始。通过返回每个字母来处理这种特殊情况。

        if n == 1:
            return {a for a in text}
    

    例如,当n=1,text='yz':

    >>> perms = gen_perms(1,'yz')
    >>> print len(perms)
    2
    >>> print sorted(perms)
    ['y', 'z']
    

    当 n=2 时,我们递归地运行该函数,因此请考虑在此行返回上面的基本情况:

               {a + b
               for a in text
               for b in gen_perms(n-1,text)}
    

    并在其上添加每个可能的字母。我将用我们输入的值替换text 重写它:

               {a + b
               for a in 'yz'
               for b in ['y','z']}
    

    希望您能看到我们会收到['yy', 'yz', 'zy', 'zz'],我们会这样做:

    >>> perms = gen_perms(2,'yz')
    >>> print len(perms)
    4
    >>> print sorted(perms)
    ['yy', 'yz', 'zy', 'zz']
    

    在这里使用集合非常好,因为如果我们将文本更改为包含重复的字母,它们就会被忽略:

    >>> perms = gen_perms(2,'yyyzz')
    >>> print len(perms)
    4
    >>> print sorted(perms)
    ['yy', 'yz', 'zy', 'zz']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      相关资源
      最近更新 更多