原文:

给定一个允许重复字符的字符串,首先打印给定字符串的 n 个排列,这样就不会重复排列。

示例:

input : string = "abcab", n = 10
output : aabbc aabcb aacbb ababc abacb
                abbac abbca abcab abcba acabb
input : string = "okok", n = 4
output : kkoo koko kook okko

方法: python 提供了一种内置的方法来查找itertools 包中存在的任何给定序列的排列。但是这种方法不能提供唯一的排列。因此,为了确保任何排列都不会重复,我们使用设置并遵循以下条件:

  • 如果置换不在集合中,打印它并将其插入集合中。增加唯一排列的计数。
  • 否则,继续下一个排列。

下面是上述方法的实现:

# python3 program to print first n unique 
# permutations of the string using itertools
from itertools import permutations
# function to print first n unique 
# permutation using itertools 
def npermute(string, n): 
    # convert the string to list and sort 
    # the characters in alphabetical order
    strlist = sorted(list(string))
    # create an iterator
    permlist = permutations(strlist)
    # keep iterating until we 
    # reach nth unique permutation
    i = 0
    permset = set()
    tempstr = '' 
    while i < n:
        tempstr = ''.join(permlist.__next__())
        # insert the string in the set
        # if it is not already included
        # and print it out.
        if tempstr not in permset:
            permset.add(tempstr)
            print(tempstr)
            i  = 1
# driver code 
if __name__ == "__main__":
    string = "ababc"
    n = 10
    npermute(string, n) 

output:

aabbc
aabcb
aacbb
ababc
abacb
abbac
abbca
abcab
abcba
acabb