Skip to content

Instantly share code, notes, and snippets.

@rch
Created May 2, 2012 19:13
Show Gist options
  • Save rch/2579405 to your computer and use it in GitHub Desktop.
Save rch/2579405 to your computer and use it in GitHub Desktop.
count char runs in a string
#
# Which would be easier to extend and generalize for top N instead of max, and infinite s1?
#
s1 = 'aabbbbcbbaab'
nmax = 0
nwrd = 0
cmax = ''
prev = ''
for c in s1:
if c == prev:
nwrd += 1
else:
if nwrd > nmax:
nmax = nwrd
cmax = prev
prev = c
nwrd = 1
print '%s%i' % (cmax, nmax)
clast = ''
chash = {}
for c in s1:
if c == clast:
nlist = chash[c]
nlist[-1] += 1
else:
clast = c
try:
chash[c].append(1)
except KeyError:
chash[c] = [1]
lst = sorted(list((max(nlist), c) for c, nlist in chash.items()), reverse=True)
print '%s%i' % lst[0][::-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment