count consecutive elements

Tim Chase python.list at tim.thechases.com
Wed Jan 13 20:35:02 EST 2021


On 2021-01-13 21:20, Bischoop wrote:
> I want to  to display a number or an alphabet which appears mostly
> consecutive in a given string or numbers or both
> Examples
> s= ' aabskaaabadcccc'
> output: c
> # c appears 4 consecutive times
>  8bbakebaoa
> output: b
> #b appears 2 consecutive times

I'd break the problem into two parts:

1) iterate over your thing (in this case, a string) and emit the item
and its correpsonding count of consecutive matches.

2) feed that into something that finds the longest run(s) output by
that.

So off the cuff, something like

  def consecutive_counter(seq):
      # I'm not sure if there's something
      # like this already in itertools
      cur = nada = object()
      count = 0
      for x in seq:
          if x == cur:
              count += 1
          else:
              if cur is not nada:
                  yield cur, count
              cur = x
              count = 1
      if cur is not nada:
          yield cur, count

  def longest(seq):
      results = []
      biggest = 0
      for item, count in seq:
          if count > biggest:
              results = [item]
              biggest = count
          elif count == biggest:
              results.append(item)
      return results, biggest

  for s in (
          "",
          "a",
          "aaa",
          "aaabbb",
          "aabskaaabadcccc",
          "aabskaaakkkkkbadcccc",
          ):
      print("Testing %r" % s)
      print(repr(longest(consecutive_counter(s))))

-tkc






More information about the Python-list mailing list