在字符串中相同的连续字母之间插入“X”

时间:2013-10-30 12:51:37

标签: python

给定一个字符串,我该如何分解它,使得在n,n + 1处没有连续的相同字母,其中n是偶数。

意思是,我如何让“abba”保持“abba”,但将“abbb”变成“abbXb”。

由于

4 个答案:

答案 0 :(得分:1)

因为每个人都喜欢单行:

strings = ['ab', 'abba', 'abbb', 'abbba', 'abbababababbbaaaa', 'abcacbbbddbabbdd']

for s in strings:
    r = ''.join('X' + v if (k and k % 2 and v == s[k - 1]) else v for (k,v) in enumerate(s))
    print s, '->', r

代码如下:查看字符串中的每个字符。如果它不是第一个并且它的索引是偶数并且它与之前的字符相同,则在字符前加'X'

输出:

ab -> ab
abba -> abba
abbb -> abbXb
abbba -> abbXba
abbababababbbaaaa -> abbababababXbbaaXaa
abcacbbbddbabbdd -> abcacbbXbdXdbabXbdXd

答案 1 :(得分:0)

做自己的功课,凯文。

def foo(text, separator):
    if len(text) < 2:
        return text

    result = ""
    for i in range(1, len(text), 2):
        if text[i] == text[i - 1]:
            result += text[i - 1] + separator + text[i]
        else:
            result += text[i-1:i+1]

    if len(text) % 2 != 0:
        result += text[-1]

    return result

print(foo("ab", "X"))
print(foo("abba", "X"))
print(foo("abbba", "X"))
print(foo("abbababababbbaaaa", "Z"))

输出:

>> ab
>> abba
>> abbXba
>> abbababababZbbaaZaa

答案 2 :(得分:0)

您可以使用itertools.groupby

from itertools import islice, groupby
import math
def solve(strs, n):
    for k, g in groupby(strs):
        lis = list(g)
        it = iter(lis)
        yield 'X'.join(''.join(islice(it, n)) for _ in xrange(int(math.ceil(len(lis)/float(n)))))

<强>演示:

>>> ''.join(solve("abba", 2))
'abba'
>>> ''.join(solve("abbb", 2))
'abbXb'
>>> ''.join(list(solve('abbbbyyyyy', 2)))
'abbXbbyyXyyXy'
>>> ''.join(solve('abbbbyyyyy', 4))
'abbbbyyyyXy'

答案 3 :(得分:0)

可能好吗?

from itertools import izip_longest

def X(s):
    s_odd = s[::2]
    s_even = s[1::2]
    output = ''
    for o, e in izip_longest(s_odd, s_even):
        output += o or ''
        if o == e:
            output += 'X'
        output += e or ''
    return output

strings = ['ab', 'abba', 'abbb', 'abbba', 'abbababababbbaaaa', 'abcacbbbddbabbdd']
for s in strings:
    print X(s)

结果:

ab
abba
abbXb
abbXba
abbababababXbbaaXaa
abcacbbXbdXdbabXbdXd

修改

更简单的版本:

def X(s):
    output = ''
    for i in range(0, len(s), 2):
        o = s[i]
        e = s[i+1] if i < len(s) - 1 else ''
        output += o
        if o == e:
            output += 'X'
        output += e
    return output

strings = ['ab', 'abba', 'abbb', 'abbba', 'abbababababbbaaaa', 'abcacbbbddbabbdd']
for s in strings:
    print X(s)