Using Python, how to print output string as -> aaa3bb2c1ddddd5 when Input string is aaabbcddddd

huangapple go评论59阅读模式
英文:

Using Python, how to print output string as -> aaa3bb2c1ddddd5 when Input string is aaabbcddddd

问题

使用Python,当输入字符串为aaabbcddddd时,如何打印输出字符串为 -> aaa3bb2c1ddddd5,我想要将实际字符值和字符在字符串中重复的次数连接起来。

def mycode(myString):
    lenstr = len(myString)
    print('字符串的长度为 '+str(lenstr))
    totalstr = ""
    for ele in myString:
        count = myString.count(ele)
        totalstr += ele + str(count)
    
    return totalstr

请注意,我对代码进行了一些修改以使其正确工作。

英文:

Using Python, how to print output string as -> aaa3bb2c1ddddd5 when Input string is aaabbcddddd
I want to concatenate actual character value and number of times a character is repeated in a string

def mycode(myString):
    lenstr = len(myString)
    print('length of string is '+str(lenstr));
    for ele in myString:
        count=0
        for character in myString:
            if character == ele:
                count = count+1
        totalstr = ele+str(count)
        
    return totalstr

答案1

得分: 2

如果字符串始终按照排序和分组一起进行,那么你可以使用collections.Counter 来执行这个操作。

from collections import Counter
inp = "aaabbcddddd"
counter = Counter(inp)
out = "".join(k * v + str(v) for k,v in counter.items())

或者在一行中:

print(''.join(k * v + str(v) for k,v in Counter(inp).items()))

输出:

aaa3bb2c1ddddd5

或者你也可以手动完成:

inp = "aaabbcddddd"
last = inp[0]
out = inp[0]
count = 1
for i in inp[1:]:
    if i == last:
        count += 1
    else:
        out += str(count)
        count = 1
        last = i
    out += i
out += str(count)
print(out)

希望这些对你有所帮助。

英文:

If the string is always sorted and grouped together like that, then you can use a collections.Counter to do it.

from collections import Counter
inp = "aaabbcddddd"
counter = Counter(inp)
out = "".join(k * v + str(v) for k,v in counter.items())

Or in one line:

print(''.join(k * v + str(v) for k,v in Counter(inp).items()))

Output:

aaa3bb2c1ddddd5

Or you can do it manually:

inp = "aaabbcddddd"
last = inp[0]
out = inp[0]
count = 1
for i in inp[1:]:
    if i == last:
        count += 1
    else:
        out += str(count)
        count = 1
        last = i
    out += i
out += str(count)
print(out)
        

答案2

得分: 1

以下是使用正则表达式替换和回调函数的一行解决方案:

inp = "aaabbcddddd"
output = re.sub(r'((\w)*)', lambda m: m.group(1) + str(len(m.group(1))), inp)
print(output)  # aaa3bb2c1ddddd5
英文:

Here is a one line solution using a regex replacement with callback:

<!-- language: python -->

inp = &quot;aaabbcddddd&quot;
output = re.sub(r&#39;((\w)*)&#39;, lambda m: m.group(1) + str(len(m.group(1))), inp)
print(output)  # aaa3bb2c1ddddd5

答案3

得分: 1

import itertools

test = 'aaabbcddddd'
out = ''.join(f"{(g := ''.join(ig))}{len(g)}" for _, ig in itertools.groupby(test))
assert out == 'aaa3bb2c1ddddd5'

英文:

Another one-liner:

import itertools

test = &#39;aaabbcddddd&#39;
out = &#39;&#39;.join(f&quot;{(g := &#39;&#39;.join(ig))}{len(g)}&quot; for _, ig in itertools.groupby(test))
assert out == &#39;aaa3bb2c1ddddd5&#39;

答案4

得分: 0

你可以这样做:

代码:

时间复杂度:O(n)

input_string = "aaabbcddddd"
res = ""
count = 1

for i in range(1, len(input_string)):
    if input_string[i] == input_string[i-1]:
        count += 1
    else:
        res += input_string[i-1] * count + str(count)
        count = 1

res += input_string[-1] * count + str(count)
print(res)  # aaa3bb2c1ddddd5

希望这有所帮助。

英文:

you can do like..

Code:

Time Complexity: O(n)

input_string=&quot;aaabbcddddd&quot;
res=&quot;&quot;
count=1

for i in range(1, len(input_string)):
    if input_string[i] == input_string[i-1]:
        count += 1
    else:
        res+=input_string[i-1]*count + str(count)
        count = 1

res+=input_string[-1]*count + str(count)
print(res) #aaa3bb2c1ddddd5

答案5

得分: 0

def char_counter_string(string):
    prev_char = None
    char_counter = 0
    output = ''
    for char_index in range(len(string) + 1):
        if char_index == len(string):
            output += str(char_counter)
            break
        if string[char_index] != prev_char and prev_char is not None:
            output += str(char_counter)
            char_counter = 0
        output += string[char_index]
        char_counter += 1
        prev_char = string[char_index]
    return output


if __name__ == '__main__':
    print(char_counter_string('aaabbcddddd'))
英文:
def char_counter_string(string):
    prev_char = None
    char_counter = 0
    output = &#39;&#39;
    for char_index in range(len(string)+1):
        if char_index == len(string):
            output += str(char_counter)
            break
        if string[char_index] != prev_char and prev_char is not None:
            output += str(char_counter)
            char_counter = 0
        output += string[char_index]
        char_counter += 1
        prev_char = string[char_index]
    return output


if __name__ == &#39;__main__&#39;:
    print(char_counter_string(&#39;aaabbcddddd&#39;))

答案6

得分: 0

这里是另一种方式,...

完全披露:只要字符连续出现的次数不超过10次,它将正常工作。也就是说,如果有11次连续出现的情况,它将无法正常工作(计数将不正确)。

这只是一个包装了reduce的函数。

from functools import reduce

def char_rep_count(in_string):
    return reduce(
             lambda acc, inp:
               (acc[:-1]+inp+str(int(acc[-1])+1))
                 if (inp==acc[-2])
                 else (acc+inp+"1"),
             in_string[1:],
             in_string[0]+"1"
           )

这是一些示例输出:

print(char_rep_count("aaabbcdddd"))
aaa3bb2c1dddd4
英文:

Here's another way, ...

Full disclosure: ... as long as the run of characters is 10 or less, it will work. I.e., if there are 11 of anything in row, this won't work (the count will be wrong).

It's just a function wrapping a reduce.

from functools import reduce

def char_rep_count(in_string):
    return reduce(
             lambda acc, inp:
               (acc[:-1]+inp+str(int(acc[-1])+1))
                 if (inp==acc[-2])
                 else (acc+inp+&quot;1&quot;),
             in_string[1:],
             in_string[0]+&quot;1&quot;
           )

And here's some sample output:

print(char_rep_count(&quot;aaabbcdddd&quot;))
aaa3bb2c1dddd4

答案7

得分: 0

我认为这满足了要求,并且速度也非常快:

s = 'aaabbcddddd'

def mycode(myString):
    if myString:
        count = 1
        rs = [prev := myString[0]]
        for c in myString[1:]:
            if c != prev:
                rs.append(f'{count}')
                count = 1
            else:
                count += 1
            rs.append(prev := c)
        rs.append(f'{count}')
        return ''.join(rs)
    return myString
英文:

I think this fulfils the brief and is also very fast:

s = &#39;aaabbcddddd&#39;

def mycode(myString):
    if myString:
        count = 1
        rs = [prev := myString[0]]
        for c in myString[1:]:
            if c != prev:
                rs.append(f&#39;{count}&#39;)
                count = 1
            else:
                count += 1
            rs.append(prev := c)
        rs.append(f&#39;{count}&#39;)
        return &#39;&#39;.join(rs)
    return myString

huangapple
  • 本文由 发表于 2023年2月18日 13:51:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定