如何找到字符串的排列? Python [英] how to find the permutations of string? python
本文介绍了如何找到字符串的排列? Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下字符串:"AAABBB"
和此字符串"--"
.
I have this string: "AAABBB"
and this string "--"
.
如何递归查找合并字符串"--AAABBB"
的所有排列?
How can i find in recursion, all of the permutations of the merged string "--AAABBB"
?
但是"AAABBB"
必须保持她的命令.例如:
But "AAABBB"
must stay at her order. For example:
--AAABBB
-A-AABBB
-AA-ABBB
.
..
.
.AAABBB--
推荐答案
以下是递归生成器的实现:
Here's a recursive generator implementation:
def comb(first_str, second_str):
if not first_str:
yield second_str
return
if not second_str:
yield first_str
return
for result in comb(first_str[1:], second_str):
yield first_str[0] + result
for result in comb(first_str, second_str[1:]):
yield second_str[0] + result
输出您的字符串:
>>> for result in comb("--", "AAABBB"):
print(result)
--AAABBB
-A-AABBB
-AA-ABBB
-AAA-BBB
-AAAB-BB
-AAABB-B
-AAABBB-
A--AABBB
A-A-ABBB
A-AA-BBB
A-AAB-BB
A-AABB-B
A-AABBB-
AA--ABBB
AA-A-BBB
AA-AB-BB
AA-ABB-B
AA-ABBB-
AAA--BBB
AAA-B-BB
AAA-BB-B
AAA-BBB-
AAAB--BB
AAAB-B-B
AAAB-BB-
AAABB--B
AAABB-B-
AAABBB--
这篇关于如何找到字符串的排列? Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文