Created
May 2, 2012 19:13
-
-
Save rch/2579405 to your computer and use it in GitHub Desktop.
count char runs in a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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