Skip to content

Instantly share code, notes, and snippets.

@inakagawa
Created March 6, 2017 07:10
Show Gist options
  • Save inakagawa/ba2789e210361f569b35784d4ab8bf64 to your computer and use it in GitHub Desktop.
Save inakagawa/ba2789e210361f569b35784d4ab8bf64 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
# hierarchical lines
class HierLines:
def __init__(self):
self.current_rank = 0
self.data = []
self.current_cursor = self.data
self.cursor_stack = []
self.cursor_stack.append(self.current_cursor)
def add_line(self,text,rank):
if(rank > self.current_rank):
self.descend_until(rank)
elif(rank < self.current_rank):
self.ascend_until(rank)
ld = LineData(text)
self.current_cursor.append(ld)
def descend_until(self, rank):
while rank > self.current_rank:
# 今のcursor をスタックに退避
# 新しいcursor を作る
self.cursor_stack.append(self.current_cursor)
new_cursor = []
self.current_cursor.append(new_cursor)
self.current_cursor = new_cursor
self.current_rank += 1
def ascend_until(self, rank):
while rank < self.current_rank:
self.current_cursor = self.cursor_stack.pop()
self.current_rank -= 1
def get_raw_data(self):
return self.data
def get_flat_data(self, D=None, F=None):
result = []
if( not F ):
F = lambda O: str(O)
if( not D):
D = self.data
if isinstance(D, list):
for DI in D:
result += self.get_flat_data(DI,F)
return result
else:
result.append(F(D))
return result
class LineData:
def __init__(self, text, modifier=None):
# modifier:
self.text = text
self.modifier = modifier
def __str__(self):
return self.text
hl = HierLines()
hl.add_line('a',1)
hl.add_line('b',2)
hl.add_line('c',3)
hl.add_line('d',1)
hl.add_line('e',3)
print(hl.get_raw_data())
print(hl.get_flat_data())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment