Created
May 7, 2016 07:48
-
-
Save tartakynov/f9f7aaa3b74763187fea41968ec64f25 to your computer and use it in GitHub Desktop.
Parenthesis String Parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
expression = simple_expression* | |
simple_expression = str | ( expression ) | |
""" | |
class Expression: | |
def __init__(self): | |
self.lst = [] | |
def add(self, expr): | |
self.lst.append(expr) | |
class Parenthesis: | |
def __init__(self, expr): | |
self.expr = expr | |
class Str: | |
def __init__(self, val): | |
self.val = val | |
class Scanner: | |
def __init__(self, input): | |
self.input = input | |
self.c = -1 | |
def peek(self): | |
return -1 if ((self.c + 1) >= len(self.input)) else self.input[self.c + 1] | |
def next(self): | |
self.c = self.c + 1 | |
return -1 if (self.c >= len(self.input)) else self.input[self.c] | |
def parseSimpleExpression(scanner): | |
c = scanner.peek() | |
ret = None | |
if (c == '('): | |
assert(scanner.next() == '(') | |
ret = Parenthesis(parseExpression(scanner)) | |
assert(scanner.next() == ')') | |
elif (c == 'a'): | |
ret = Str(scanner.next()) | |
return ret | |
def parseExpression(scanner): | |
expr = Expression() | |
while (True): | |
c = scanner.peek() | |
if (c == 'a' or c == '('): | |
expr.add(parseSimpleExpression(scanner)) | |
else: | |
break | |
return expr | |
def printExpression(expr, depth): | |
for sub in expr.lst: | |
if isinstance(sub, Str): | |
print ' ' * (depth * 2), sub.val | |
elif isinstance(sub, Parenthesis): | |
print ' ' * (depth * 2), '(' | |
printExpression(sub.expr, depth + 1) | |
print ' ' * (depth * 2), ')' | |
elif isinstance(sub, Expression): | |
printExpression(sub, depth + 1) | |
if __name__ == '__main__': | |
scanner = Scanner('aa(aa(a))aa(a)()(a(a(a(a))))') | |
expr = parseExpression(scanner) | |
printExpression(expr, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment