-1

I have this string: "AAABBB" and this string "--".

How can i find in recursion, all of the permutations of the merged string "--AAABBB"?

But "AAABBB" must stay at her order. For example:

--AAABBB 
-A-AABBB 
-AA-ABBB 
. 
.. 
. 
.AAABBB-- 
3
  • 3
    Its called Combination not permutation. Commented Nov 22, 2013 at 8:22
  • 2
    Where do the dots come from? Commented Nov 22, 2013 at 8:26
  • 1
    is this a hw assignment? what have you tried so far? Commented Nov 22, 2013 at 8:38

2 Answers 2

3

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

Output with your strings:

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

Comments

2
from itertools import combinations

def dashed_comb(base_str, exp_len):
    for comb in combinations(range(exp_len), exp_len-len(base_str)):
        letters = iter(base_str)
        yield ''.join('-' if x in comb else letters.next()
                               for x in xrange(exp_len))

recursive one (provide here as it is twice faster that itertools based):

def recursive_dc(base_str, exp_len):
    if len(base_str) == 0:
        yield '-' * exp_len
    elif len(base_str) == exp_len:
        yield base_str
    else:
        for x in recursive_dc(base_str, exp_len-1):
            yield '-' + x
        for x in recursive_dc(base_str[1:], exp_len-1):
            yield base_str[0] + x 

Sample output:

>>> for dc in dashed_comb('AAB', 5):
...     print dc
...
...
--AAB
-A-AB
-AA-B
-AAB-
A--AB
A-A-B
A-AB-
AA--B
AA-B-
AAB--

2 Comments

I am sorry. I don't see recursion in this :)
@thefourtheye ooops, missed recursion requirement :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.