算法分割字符串成子包括空分区 [英] Algorithm to partition a string into substrings including null partitions

查看:200
本文介绍了算法分割字符串成子包括空分区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:
设P为一组的划分字符串s所有可能的方式为相邻,并可能为空字符串。我正在寻找一个优雅的算法来解决这个问题。

背景方面:
给定字符串(S,W)的元组中,定义P(S)和P(w)的如上。存在一个特定分区ř∈P(S)和T∈P(w)的能产生最少数目的子字符串的Levenshtein(插入,删除和替换)的编辑。

这是例子:
分区字符串foo到5子,其中ε是一个空字符串:

  [ε,ε,F,O,O]
[ε,女,ε,O,O]
[ε,F,O,ε,O]
[ε,F,O,O,ε]

[F,ε,ε,O,O]
[F,ε,邻,ε,O]
[F,ε,O,O-,ε]

[F,O,ε,ε,O]
[F,O,ε,邻,ε]

[F,O,O,ε,ε]
 

解决方案

怎么样一个简单的递归的方法呢?

  DEF部分(S,N,pre):
    如果s =='':
        返回[pre +'。 * N]
    ELIF N'GT; 0:
        RES = []
        如果n>透镜):
            RES + =一部分(S,N-1,pre +'。')
        如果len(S)> 0:
            水库+ =部分(S [1:]中,n-1,pre + S [0])
        回报水库
 

结果:

 >>>打印部件('富',5,'')
['富..','fo.o.','fo..o','f.oo.','富','f..oo','.foo。','.fo。 O','.f.oo','..foo']
 

The problem:
Let P be the set of all possible ways of partitioning string s into adjacent and possibly null substrings. I'm looking for an elegant algorithm to solve this problem.

Background context:
Given a tuple of strings (s, w), define P(s) and P(w) as above. There exists a particular partition R ∈ P(s) and T ∈ P(w) that yields the least number of substring Levenshtein (insertion, deletion and substitution) edits.

An example:
Partition string "foo" into 5 substrings, where ε is a null substring:

[ε, ε, f, o, o]  
[ε, f, ε, o, o]  
[ε, f, o, ε, o]  
[ε, f, o, o, ε]

[f, ε, ε, o, o]  
[f, ε, o, ε, o]  
[f, ε, o, o, ε]

[f, o, ε, ε, o]  
[f, o, ε, o, ε]

[f, o, o, ε, ε]

解决方案

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

这篇关于算法分割字符串成子包括空分区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆