在Python中输出给定字符串的所有排列组合

云课堂学Python 2024-04-08 00:07:04

在本文中,我们将与您分享两种输出给定字符串所有排列组合的方法。

使用 permutations() 函数输出字符串所有排列组合

使用 permutations() 函数前,你应该了解 itertools 模块,因为这个模块将有助于找到给定字符串的所有排列。itertools 模块提供了一个函数 permutations(),permutations()可以返回元素的所有排列组合。

「语法格式:」

itertools.permutations(iterable, r=None)

「返回:」

序列中元素的 r 长度排列。如果 r 省略或为 None ,则 r 默认为序列的长度。

「示例:」

from itertools import permutationsa=permutations('abc')for i in a: print(i)

运行结果:

('a', 'b', 'c')

('a', 'c', 'b')

('b', 'a', 'c')

('b', 'c', 'a')

('c', 'a', 'b')

('c', 'b', 'a')

指定参数:r=2

from itertools import permutationsa=permutations('abc',r=2)for i in a: print(i)

运行结果:

('a', 'b')

('a', 'c')

('b', 'a')

('b', 'c')

('c', 'a')

('c', 'b')

要输出给定字符串的所有排列,我们可以按以下步骤实现:

从 itertools 模块导入 permutations() 函数。接受用户输入字符串。使用 permutations() 函数返回所有排列。连接所有排列为字符串。输出所有排列字符串。from itertools import permutationsstr=input('请输入一个字符串:')b=[]p=permutations(str)for k in list(p): r=''.join(k) b.append(r)print(f'字符{str}全排列:{b}')

运行结果:

请输入一个字符串:abc

字符abc全排列:['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

自定义函数输出字符串所有排列组合#将列表转换为字符串def toStr(List): return ''.join(List) # 自定义递归函数def mypermute(a, l, r): if l == r: print (toStr(a)) else: for i in range(l, r + 1): a[l], a[i] = a[i], a[l] mypermute(a, l + 1, r) a[l], a[i] = a[i], a[l] str=input('请输入一个字符串:')n = len(str)a = list(str)print(f'字符{str}全排列:')mypermute(a, 0, n-1)

运行结果:

请输入一个字符串:abc

字符abc全排列:

abc

acb

bac

bca

cba

cab

文章创作不易,如果您喜欢这篇文章,请关注、点赞并分享给朋友。如有意见和建议,请在评论中反馈!

0 阅读:0

云课堂学Python

简介:感谢大家的关注