daily pastebin goal
14%
SHARE
TWEET

Untitled

a guest Jul 17th, 2018 46 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. s = """A
  2.     B
  3.         C
  4.         D
  5.     E
  6. F
  7. G
  8.     H
  9.         I
  10. K
  11.    L"""
  12.  
  13. class CNode:
  14.    children, parent, data = [], None, ""
  15.  
  16.    def __init__(self, parent, data):
  17.       self.children = []
  18.       self.parent = parent
  19.       self.data = data
  20.  
  21.    def to_string(self):
  22.       return "[" + self.data + ''.join([c.to_string() for c in self.children]) + "]"
  23.  
  24.    def to_dict(self):
  25.       return dict((c.data, c.to_dict()) for c in self.children)
  26.  
  27. import re
  28. r = re.compile(r'\S')
  29.  
  30. def get_indent_value(line):
  31.    m = r.search(line)
  32.    return (m.start(), m.group(0))
  33.  
  34. def get_parent(node, level):
  35.    if level == 0:
  36.       return node
  37.    return get_parent(node.parent, level-1)
  38.  
  39. root = CNode(None,"")
  40. parent = root
  41. lines = s.split('\n')
  42. level = 0
  43. for line in lines:
  44.    i, v = get_indent_value(line)
  45.    if i < level:
  46.       parent = get_parent(parent, level-i)
  47.    if i > level:
  48.       parent = current
  49.    current = CNode(parent,v)
  50.    parent.children.append(current)
  51.    level = i
  52.  
  53. print root.to_string()
  54. print root.to_dict()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top