计算连续字符

发布于 2021-01-29 19:32:25

如何在Python中计算连续字符,以查看每个唯一数字在下一个唯一数字之前重复的次数?

起初,我以为我可以做类似的事情:

word = '1000'

counter=0
print range(len(word))


for i in range(len(word)-1):
    while word[i]==word[i+1]:
        counter +=1
        print counter*"0"
    else:
        counter=1
        print counter*"1"

这样,我就可以看到每个唯一数字重复的次数。但是,这当然会在i达到最后一个值时超出范围。

在上面的示例中,我希望Python告诉我1重复1,而0重复3次。但是,由于我的while语句,上面的代码失败了。

我知道您可以使用内置函数来做到这一点,并且希望采用这种方式的解决方案。

关注者
0
被浏览
47
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    一种“那种方式”的解决方案,仅包含基本声明:

    word="100011010" #word = "1"
    count=1
    length=""
    if len(word)>1:
        for i in range(1,len(word)):
           if word[i-1]==word[i]:
              count+=1
           else :
               length += word[i-1]+" repeats "+str(count)+", "
               count=1
        length += ("and "+word[i]+" repeats "+str(count))
    else:
        i=0
        length += ("and "+word[i]+" repeats "+str(count))
    print (length)
    

    输出:

    '1 repeats 1, 0 repeats 3, 1 repeats 2, 0 repeats 1, 1 repeats 1, and 0 repeats 1'
    #'1 repeats 1'
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看