Skip to content Skip to sidebar Skip to footer

How To Find The Permutations Of String? Python

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

Solution 1:

Here's a recursive generator implementation:

defcomb(first_str, second_str):
    ifnot first_str:
        yield second_str
        returnifnot second_str:
        yield first_str
        returnfor 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:

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

Solution 2:

from itertools import combinations

defdashed_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):

defrecursive_dc(base_str, exp_len):
    iflen(base_str) == 0:
        yield'-' * exp_len
    eliflen(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--

Post a Comment for "How To Find The Permutations Of String? Python"