Skip to content

Instantly share code, notes, and snippets.

@samidarko
Last active August 14, 2016 08:39
Show Gist options
  • Save samidarko/a4b7e299f17bb9ff33366541dd340970 to your computer and use it in GitHub Desktop.
Save samidarko/a4b7e299f17bb9ff33366541dd340970 to your computer and use it in GitHub Desktop.
Count the number of occurrences in a string over consumption
# python 3
def span(string, char):
i = 0
while i < len(string) and string[i] == char:
i += 1
return string[0:i], string[i:]
def count_occurrences(string):
if string:
print(len(span(string, string[0])[0]), string[0], sep='', end='')
count_occurrences(span(string, string[0])[1])
else:
print()
count_occurrences('aaaaabbbbccccccaaaaaaa') # '5a4b6c7a'
# not my solution but very concise (https://www.linkedin.com/groups/25827/25827-6166706414627627011)
import itertools as it
"".join(str(sum(1 for _ in j))+i for i,j in it.groupby('5a4b6c7a')) #'5a4b6c7a'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment