Python中字符串的受限排列 [英] Restricted Permutations of Strings in Python

查看:81
本文介绍了Python中字符串的受限排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中执行以下操作?

How can I do the following in Python?

给出两个字符串.打印两个字符串的所有交织. 交织意味着如果B在A之后,则它也应该在交织的字符串中在A之后. 前任- AB和CD A B C D ACBD 交流数据库 中央商务区 计算机辅助设计 CDAB

Given two strings. Print all the interleavings of the two strings. Interleaving means that the if B comes after A, it should also come after A in the interleaved string. ex- AB and CD ABCD ACBD ACDB CABD CADB CDAB

推荐答案

这实际上是一个遍历树的问题(即是否沿着一个字符串或另一个字符串前进的决策树).通常,解决树上行走问题的最简单方法是递归解决方案.

This is effectively a tree-walking problem (namely, the decision tree of whether to advance along one string or the other). Oftentimes, the simplest way to approach a tree-walking problem is a recursive solution.

这是一个例子:

def ordered_permutations(str1, str2):
    perms = []
    if len(str1) + len(str2) == 1:
        return [str1 or str2]
    if str1:
        for item in ordered_permutations(str1[1:], str2):
            perms.append(str1[0] + item)
    if str2:
        for item in ordered_permutations(str1, str2[1:]):
            perms.append(str2[0] + item)
    return perms

这篇关于Python中字符串的受限排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆