📜  使用Python的itertools打印字符串的前n个不同的排列

📅  最后修改于: 2021-04-22 07:06:59             🧑  作者: Mango

给定一个允许重复字符的字符串,请打印给定字符串的前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) 
输出:
aabbc
aabcb
aacbb
ababc
abacb
abbac
abbca
abcab
abcba
acabb