Mike
Mike

Reputation: 31

How should I read the input data?

For example, I have the following input data:

(( 12 3 ) 42 )

I want to treat each integer value of the input data. This is an example of the general input data presentation.

Just for additional information:

Such presentation is corresponding to the binary tree with marked leaves:

   /\
  /\ 42
 12 3

Upvotes: 3

Views: 194

Answers (4)

Odomontois
Odomontois

Reputation: 16308

I wrote this script. It may be helpful

import tokenize,StringIO
def parseNode(tokens):
    l = []
    while True:
        c = next(tokens)
        if c[1] == '(':
            l.append(parseNode(tokens))
        elif c[1] == ')':
            return l
        elif c[0] == tokenize.NUMBER:
            l.append(int(c[1]))
def parseTree(string):
    tokens = tokenize.generate_tokens(StringIO.StringIO(string).readline)
    while next(tokens)[1] != '(' : pass
    return parseNode(tokens)
print parseTree('(( 12 3 ) 42 15 (16 (11 2) 2) )')

Upvotes: 1

Eric Snow
Eric Snow

Reputation: 1198

something like the following should work:

import re
newinput = re.sub(r"(\d) ", r"\1, ", input)
newinput = re.sub(r"\) ", r"), ", newinput)
eval(newinput)

Upvotes: 0

cji
cji

Reputation: 6705

here is good list of resources you could use. I would suggest PLY

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 881765

I recommend pyparsing for this parsing task -- here, for example, is a pyparsing-based parsers for S-expressions... probably much richer and more powerful than what you need, but with a really limited understanding of Python and pyparsing you can simplify it down as much as you require (if at all -- it's quite able to perform your task already, as a subset of the broader set it covers;-).

Upvotes: 3

Related Questions