查找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中的内置模块,是处理迭代器的工具集合。 它是Python最有用的模块。 在这里,用户提供了一个字符串,我们必须在Python中打印给定字符串的所有可能排列 。 众所周知,置换是按照组成不同组的特定顺序或序列排列组或集合的元素的一种方式。 我们所有人都使用笔和纸计算了排列,但是在这里我们将在很短的时间内使用Python编程语言来完成排列。

Algorithm to solve the problem:

解决问题的算法:

  1. Initially, we will import the permutation function from the itertools module.

    最初,我们将从itertools模块导入置换函数。

  2. Take the string from the user and assign it in a variable s.

    从用户处获取字符串,并将其分配给变量s 。

  3. Generate all permutation using the permutation function and assign it in a variable p.

    使用置换函数生成所有置换,并将其分配给变量p 。

  4. Since all elements of p are in tuple form. So, convert it in the list.

    由于p的所有元素都是元组形式。 因此,将其转换为列表。

  5. 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值