how to find the permutations of string? python [cl

2019-09-09 16:50发布

问题:

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-- 

回答1:

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--


回答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--