Algorithm to partition a string into substrings including null partitions

我的梦境 提交于 2019-12-04 19:17:01

How about a simple recursive approach?

def part(s, n, pre):
    if s == '':
        return [pre + '.' * n]
    elif n > 0:
        res = []
        if n > len(s):
            res += part(s, n-1, pre + '.')
        if len(s) > 0:
            res += part(s[1:], n-1, pre + s[0])
        return res

Result:

>>> print part('foo', 5, '')
['foo..', 'fo.o.', 'fo..o', 'f.oo.', 'f.o.o', 'f..oo', '.foo.', '.fo.o', '.f.oo', '..foo']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!