Python itertools Module
Python itertools模塊
"itertools" are an inbuilt module in Python which is a collection of tools for handling iterators. It is the most useful module of Python. Here, a string is provided by the user and we have to print all the possible permutations of the given string in Python. As we all know the permutation is a way of arranging the elements of a group or set in a specific order or sequence which makes a different group. We all have calculated the permutations by using the pen and paper but here we will do this by using the Python programming language in a very small time.
“ itertools”是Python中的內置模塊,是處理迭代器的工具集合。 它是Python最有用的模塊。 在這里,用戶提供了一個字符串,我們必須在Python中打印給定字符串的所有可能排列 。 眾所周知,置換是按照組成不同組的特定順序或序列排列組或集合的元素的一種方式。 我們所有人都使用筆和紙計算了排列,但是在這里我們將在很短的時間內使用Python編程語言來完成排列。
Algorithm to solve the problem:
解決問題的算法:
Initially, we will import the permutation function from the itertools module.
最初,我們將從itertools模塊導入置換函數。
Take the string from the user and assign it in a variable s.
從用戶處獲取字符串,并將其分配給變量s 。
Generate all permutation using the permutation function and assign it in a variable p.
使用置換函數生成所有置換,并將其分配給變量p 。
Since all elements of p are in tuple form. So, convert it in the list.
由于p的所有元素都是元組形式。 因此,將其轉換為列表。
At last, add all list elements and print it which is our possible permutations.
最后,添加所有列表元素并打印出來,這是我們可能的排列方式。
Let's start writing the Python program by implementing the above algorithm in a simple way.
讓我們通過簡單的方法來實現上述算法,開始編寫Python程序。
Python程序查找給定字符串的所有排列 (Python program to find all permutations of a given string)
# importing the module
from itertools import permutations
# input the sting
s=input('Enter a string: ')
A=[]
b=[]
p=permutations(s)
for k in list(p):
A.append(list(k))
for j in A:
r=''.join(str(l) for l in j)
b.append(r)
print('Number of all permutations: ',len(b))
print('All permutations are: ')
print(b)
Output
輸出量
Enter a string: ABC
Number of all permutations: 21
All permutations are:
['ABC', 'ABC', 'ACB', 'ABC', 'ACB', 'BAC', 'ABC', 'ACB', 'BAC', 'BCA', 'ABC',
'ACB', 'BAC', 'BCA', 'CAB', 'ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']
翻譯自: https://www.includehelp.com/python/find-all-permutations-of-a-given-string.aspx