开发者

decomposing a string into known patterns

开发者 https://www.devze.com 2023-01-06 11:18 出处:网络
Here\'s the python list of strings: patterns = [ \"KBKKB\", \"BBBK\", \"BKB\", \"KBBB\", \"KBB\", \"BKBB\", \"BBKB\",

Here's the python list of strings:

patterns = [ "KBKKB", "BBBK", "BKB", "KBBB", "KBB", "BKBB", "BBKB", "KKBKB", "BKBK", "KBKB", "KBKBK", "BBK", "BB", "BKKB", "BBB", "KBBK", "BKKBK", "KB", "KBKBK", "KKBKKB", "KBK", "BBKBK", "BBBB", "BK", "KKBKBK", "KBBKB", "BBKKB", "KKKKBB", "KKB" ]

I have an input string that consist of K and B only of arbitrary length. I want to know all the possible complete decompositions of the input string. Just an example a string of 8 B:

BBBBBBBB

开发者_如何学JAVA

Here are possible decompositions

BB BB BB BB BB

BBBB BBBB

BBBB BB BB

BB BB BBBB

BBB BBB BB

BB BBB BBB

Can anyone guide me how to go about it? I am not much concerned about efficiency right now.


Here's one way using recursion:

def getPossibleDecompositions(s):
    if s == '':
        yield []
    else:
        for pattern in patterns:
            if s.startswith(pattern):
                for x in getPossibleDecompositions(s[len(pattern):]):
                    yield [pattern] + x

for x in getPossibleDecompositions('BBBBBBBB'):
    print x
0

精彩评论

暂无评论...
验证码 换一张
取 消