Skip to content

Instantly share code, notes, and snippets.

@ytaki0801
Created February 8, 2022 14:20
Show Gist options
  • Save ytaki0801/828501cb6497ea5111bfd43f3ae6bd22 to your computer and use it in GitHub Desktop.
Save ytaki0801/828501cb6497ea5111bfd43f3ae6bd22 to your computer and use it in GitHub Desktop.
Parser for simplest S-expression or array-expression of parentheses by using 1-character input in Python
from sys import stdin
LH = False
def get_token():
def put_c1(x): global LH; LH = x
def null_c1(): global LH; LH = False
def get_c1():
if not LH:
try: return stdin.read(1)
except EOFError: pass
else: lh = LH; null_c1(); return lh
def tstring(t): return ''.join(t)
def skip_spaces():
c = get_c1();
while c in ' \n\r\x1a': c = get_c1()
put_c1(c)
c = get_c1(); t = []
while True:
if c in ' \n\r\x1a':
skip_spaces();
if not t: c = get_c1()
else: return tstring(t)
elif c == '(': skip_spaces(); return c
elif c == ')':
if not t: return c
else: put_c1(c); return tstring(t)
else: t = t + [c]; c = get_c1()
def sread():
def slist():
t = get_token()
if t == ')': return []
elif t == '(': h = slist(); return [h] + slist()
else: return [t] + slist();
t = get_token()
return slist() if t == '(' else t
print(sread())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment