查找Python中给定字符串的所有排列
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中的內(nèi)置模塊,是處理迭代器的工具集合。 它是Python最有用的模塊。 在這里,用戶提供了一個(gè)字符串,我們必須在Python中打印給定字符串的所有可能排列 。 眾所周知,置換是按照組成不同組的特定順序或序列排列組或集合的元素的一種方式。 我們所有人都使用筆和紙計(jì)算了排列,但是在這里我們將在很短的時(shí)間內(nèi)使用Python編程語(yǔ)言來(lái)完成排列。
Algorithm to solve the problem:
解決問(wèn)題的算法:
Initially, we will import the permutation function from the itertools module.
最初,我們將從itertools模塊導(dǎo)入置換函數(shù)。
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.
使用置換函數(shù)生成所有置換,并將其分配給變量p 。
Since all elements of p are in tuple form. So, convert it in the list.
由于p的所有元素都是元組形式。 因此,將其轉(zhuǎn)換為列表。
At last, add all list elements and print it which is our possible permutations.
最后,添加所有列表元素并打印出來(lái),這是我們可能的排列方式。
Let's start writing the Python program by implementing the above algorithm in a simple way.
讓我們通過(guò)簡(jiǎn)單的方法來(lái)實(shí)現(xiàn)上述算法,開(kāi)始編寫(xiě)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
總結(jié)
以上是生活随笔為你收集整理的查找Python中给定字符串的所有排列的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: weakhashmap_Java Wea
- 下一篇: 操作系统文件分配策略_操作系统中的文件分