0

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

意思是,我怎样才能让“abba”保持“abba”,但把“abbb”变成“abbXb”。

谢谢

4

4 回答 4

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
于 2013-10-30T13:12:10.913 回答
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)
于 2013-10-30T13:24:22.070 回答
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
于 2013-10-30T13:07:59.930 回答
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'
于 2013-10-30T13:08:16.933 回答