python - Tracking on/off state in a sequence -
python - Tracking on/off state in a sequence -
i have generator function tracks whether between pair of events-- "start" event , "end" event. example, examining tokens , reporting whether between comment delimiters "/*" , "*/" (non-nesting). next code works, there nice itertools combination or logical restructuring simplify (and/or create more "pythonic")?
def tokspan(starttok, endtok, stream): within = false tok in stream: if (not inside) , tok == starttok: within = true yield (inside, tok) if within , tok == endtok: within = false tstream = "int x; /* non-nesting comment /* etc. */ x=1; main();".split() status, tok in tokspan("/*", "*/", tstream): print(status, tok) the above (intentionally) returns true boundary tokens (/* , */), that's not particularly important. if have approach happens exclude 1 or both boundaries (like python ranges do), i'd still know it.
the simplification can think of rewriting logic around setting/resetting inside:
def tokspan(starttok, endtok, stream): within = false tok in stream: within |= (tok == starttok) yield (inside, tok) within &= (tok != endtok) whether makes code more or less readable in eye of beholder.
python generator
Comments
Post a Comment