【发布时间】:2014-01-05 03:21:38
【问题描述】:
所以我正在尝试编写一个函数来查找 2 个字符串的所有替代连接。说x = '12'和y = 'ab',那么预期结果是['ab12', 'a1b2', 'a12b', '1ab2', '1a2b', '12ab']。我编写了以下程序:
# [ list of sequences where each seq is a concat of s and t ]
def g( s, t ) :
#
if ( s == "" ) :
return [ t ]
elif ( t == "" ) :
return [ s ]
else :
res = []
for i in xrange( len(s) ) :
for j in xrange( 1, len(t) + 1 ) :
res.extend( [ s[:i] + t[:j] + x for x in g( s[i:], t[j:] ) ] )
#
res.append( s + t )
return res
它输出正确的结果,但有些序列有重复:
In [22]: r = g( "12", "ab" )
[ (x, r.count(x)) for x in set( r ) ]
Out[22]: [('ab12', 2), ('12ab', 1), ('1ab2', 2), ('a12b', 1), ('1a2b', 1), ('a1b2', 1)]
如何避免重复? (我不想检查是否已经添加了元素;我对生成唯一序列的“真正”方式感兴趣)
【问题讨论】:
标签: algorithm concatenation dynamic-programming combinatorics