簡體   English   中英

C ++或Python中字符串的所有排列的算法

[英]Algorithm for all permutations of a string in C++ or Python

我需要用c ++或python編寫一個函數,該函數獲取字符串並顯示所有可以加擾的選項。 例如-scramble(“ abc”)將打印-

abc
acb
bac
bca
cab
cba

當然,並非只有單詞的長度為3。

在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

這是一個較短的遞歸函數,用於查找字符串中字母的所有排列:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM