2

How can I do the following in Python?

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

1
  • 1
    What have you tried? Do you have any code of your own yet, which you can show us? Commented Oct 26, 2012 at 23:03

2 Answers 2

8

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.


Here's an example:

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
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, but it is returning an empty list when I run it...any ideas why? I am new to coding!
Was missing a base case. Fixed now. However, I'd suggest trying to figure out exactly how it's working so you can learn from it, rather than just asking other people to write your code for you.
1

Hats off to @Amber for recognizing the problem and giving a very elegant solution to it.

Here's my two cents worth (just printing out the answers):

def interleave(L1, L2, answer=None):
    if answer is None:
        answer = ''
    if not L1 and not L2:
        print answer
    else:
        if L1:
            a = answer + L1[0]
            interleave(L1[1:], L2, a)
        if L2:
            ans = answer + L2[0]
            interleave(L1, L2[1:], and)

>>> interleave('ab', 'cd')
abcd
acbd
acdb
cabd
cadb
cdab

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.