2011年7月5日火曜日

唐突に写経

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク
いつまでつづくのやら。

import StringIO
buf = StringIO.StringIO('9-5+2')

lookahead = ''

def expr():
  term()
  while True:
    if lookahead == '+':
      match('+')
      term()
      print '+',
    elif lookahead =='-':
      match('-')
      term()
      print '-',
    else:
      break


def term():
  if lookahead.isdigit():
    print lookahead,
    match(lookahead)
  else:
    error()

def match(t):
  global lookahead
  if lookahead == t:
    lookahead = buf.read(1)
  else:
    error()

def error():
  print 'syntax error'
  raise



lookahead = buf.read(1)
expr()
print '\n'

0 件のコメント: