How to read input?

For example, I have the following input:

((12 3) 42)

I want to process every integer value of the input. This is an example of representing a common input.

For additional information only:

This representation corresponds to a binary tree with marked sheets:

   /\
  /\ 42
 12 3
+3
source share
4 answers

pyparsing - , , S-... , , , Python pyparsing ( - , , ; -).

+3

script.

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) )')
+1

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

0
source

the following should work:

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

Source: https://habr.com/ru/post/1759633/


All Articles