Skip to content

Instantly share code, notes, and snippets.

@rch
Created January 27, 2012 18:15
Show Gist options
  • Save rch/1690109 to your computer and use it in GitHub Desktop.
Save rch/1690109 to your computer and use it in GitHub Desktop.
Count runs of extra spaces?
from functools import partial, wraps
def coroutine(func):
# Based on http://www.dabeaz.com/coroutines/coroutine.py
@wraps(func)
def start(*args,**kwargs):
cr = func(*args,**kwargs)
cr.next()
return cr
return start
@coroutine
def reps():
""" comment preserved by @wraps in coroutine. """
seq = ''
while True:
c = (yield)
if c is None:
lst = seq
seq = ''
yield lst
else:
seq += c
yield ''
def chk(c, gaps):
if c == ' ':
rsp = gaps.send(c)
gaps.next()
else:
rsp = gaps.send(None)
gaps.next()
return len(rsp)
if __name__ == '__main__':
s = 'hello there to everyone in the world' # extra spaces!
chkr = partial(chk, gaps=reps())
print sum(v for v in map(chkr, s) if v >= 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment