[英]How can I count the number of characters in a string and displaying the character and amount
单词问题:
创建一个 function 将压缩技术应用于字符串并返回结果压缩字符串。 更正式地说,一个块是尽可能长的相同符号的 substring。 块将以压缩形式表示为块的长度,后跟该块中的符号。 字符串的编码是字符串中每个块按照它们在字符串中出现的顺序的表示。 给定一个字符序列,编写一个程序以这种格式对它们进行编码。
示例输入:
打印(rleEncode('WWWWWWWBWWWWWWWBBW'))
示例 Output:
'W7B1W7B2W1'
到目前为止,我创建了一个计数器和一个 for 循环,它将遍历 sting 中的每个字符,我不知道如何完成它
def rleEncode(s: str) -> str: count = 0 index = "" for i in range(len(s)): if s[i] in index: index.append(i) count += 1 return count, index
我认为这个概率。 你在找什么? 在纯 Python 中:
from itertools import groupby
s = '...your string....'
ans = ''
for k, g in groupby(s):
ans += ''.join(k + str(len(list(g))))
print(ans)
'W7B1W7B2W1'
即使使用 Python lib - groupby,也没有。 正如您所看到的,它有更多的代码行......以及一些确定从哪里开始/停止新计数的逻辑。
def encode(s: str) -> str:
count = 1
res = ''
# the first character
res += s[0]
# loop, skipping last one
for i, char in enumerate(s[:-1]):
if s[i] == s[i+1]: # current == next char.
count += 1 # increment count
else: # char changing
if count >= 1:
res += str(count) # convert int to string and add
res += s[i+1]
count = 1 # reset the count
# finally the last one
if count >= 1: # if the char is ONE.
res += str(count)
return res
print(encode(s)) # W7B1W7B2W
print(encode('ABBA')) # A1B2A1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.