Count consecutive characters

后端 未结 9 1615
别那么骄傲
别那么骄傲 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:26

    Totals (without sub-groupings)

    #!/usr/bin/python3 -B
    
    charseq = 'abbcccffffdd'
    distros = { c:1 for c in charseq  }
    
    for c in range(len(charseq)-1):
        if charseq[c] == charseq[c+1]:
            distros[charseq[c]] += 1
    
    print(distros)
    

    I'll provide a brief explanation for the interesting lines.

    distros = { c:1 for c in charseq  }
    

    The line above is a dictionary comprehension, and it basically iterates over the characters in charseq and creates a key/value pair for a dictionary where the key is the character and the value is the number of times it has been encountered so far.

    Then comes the loop:

    for c in range(len(charseq)-1):
    

    We go from 0 to length - 1 to avoid going out of bounds with the c+1 indexing in the loop's body.

    if charseq[c] == charseq[c+1]:
        distros[charseq[c]] += 1
    

    At this point, every match we encounter we know is consecutive, so we simply add 1 to the character key. For example, if we take a snapshot of one iteration, the code could look like this (using direct values instead of variables, for illustrative purposes):

    # replacing vars for their values
    if charseq[1] == charseq[1+1]:
        distros[charseq[1]] += 1
    
    # this is a snapshot of a single comparison here and what happens later
    if 'b' == 'b':
        distros['b'] += 1
    

    You can see the program output below with the correct counts:

    ➜  /tmp  ./counter.py
    {'b': 2, 'a': 1, 'c': 3, 'd': 4}
    

提交回复
热议问题