Count consecutive characters

后端 未结 9 1526
别那么骄傲
别那么骄傲 2020-11-28 06:44

How would I count consecutive characters in Python to see the number of times each unique digit repeats before the next unique digit?

At first, I thought I could do

相关标签:
9条回答
  • 2020-11-28 07:33

    Unique method:- In case if you are just looking for counting consecutive 1's Using Bit Magic: The idea is based on the concept that if we AND a bit sequence with a shifted version of itself, we’re effectively removing the trailing 1 from every sequence of consecutive 1s.

      11101111   (x)
    & 11011110   (x << 1)
    ----------
      11001110   (x & (x << 1)) 
        ^    ^
        |    |
    

    trailing 1 removed So the operation x = (x & (x << 1)) reduces length of every sequence of 1s by one in binary representation of x. If we keep doing this operation in a loop, we end up with x = 0. The number of iterations required to reach 0 is actually length of the longest consecutive sequence of 1s.

    0 讨论(0)
  • 2020-11-28 07:34

    A solution "that way", with only basic statements:

    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)
    

    Output :

    '1 repeats 1, 0 repeats 3, 1 repeats 2, 0 repeats 1, 1 repeats 1, and 0 repeats 1'
    #'1 repeats 1'
    
    0 讨论(0)
  • 2020-11-28 07:34

    You only need to change len(word) to len(word) - 1. That said, you could also use the fact that False's value is 0 and True's value is 1 with sum:

    sum(word[i] == word[i+1] for i in range(len(word)-1))
    

    This produces the sum of (False, True, True, False) where False is 0 and True is 1 - which is what you're after.

    If you want this to be safe you need to guard empty words (index -1 access):

    sum(word[i] == word[i+1] for i in range(max(0, len(word)-1)))
    

    And this can be improved with zip:

    sum(c1 == c2 for c1, c2 in zip(word[:-1], word[1:]))
    
    0 讨论(0)
提交回复
热议问题