这是一个涵盖您所需要的大部分解决方案。
像任何树算法一样,递归树的子级,并在每个节点上合并结果。诀窍是:
display()返回一个矩形的文本,例如:
aaaaaaaaaaaaaaaaaa
大部分矩形将为空白。仅返回文本的矩形可轻松组合结果。我们将使用以下两个辅助函数,一个用于测量块的宽度,另一个用于将块水平组合成更大的块:
def block_width(block): try: return block.index('n') except ValueError: return len(block)def stack_str_blocks(blocks): """Takes a list of multiline strings, and stacks them horizontally. For example, given 'aaanaaa' and 'bbbbnbbbb', it returns 'aaa bbbbnaaa bbbb'. As in: 'aaa + 'bbbb = 'aaa bbbb aaa' bbbb' aaa bbbb' Each block must be rectangular (all lines are the same length), but blocks can be different sizes. """ builder = [] block_lens = [block_width(bl) for bl in blocks] split_blocks = [bl.split('n') for bl in blocks] for line_list in itertools.izip_longest(*split_blocks, fillvalue=None): for i, line in enumerate(line_list): if line is None: builder.append(' ' * block_lens[i]) else: builder.append(line) if i != len(line_list) - 1: builder.append(' ') # Padding builder.append('n') return ''.join(builder[:-1])
看到这是怎么回事?子级返回一个显示自己及其后代的矩形,每个节点会将这些矩形组合成一个包含自身的较大矩形。其余代码仅呈现破折号和加号:
class Node: def display(self): # Here if not self.children: return self.name child_strs = [child.display() for child in self.children] child_widths = [block_width(s) for s in child_strs] # How wide is this block? display_width = max(len(self.name), sum(child_widths) + len(child_widths) - 1) # Determines midpoints of child blocks child_midpoints = [] child_end = 0 for width in child_widths: child_midpoints.append(child_end + (width // 2)) child_end += width + 1 # Builds up the brace, using the child midpoints brace_builder = [] for i in xrange(display_width): if i < child_midpoints[0] or i > child_midpoints[-1]: brace_builder.append(' ') elif i in child_midpoints: brace_builder.append('+') else: brace_builder.append('-') brace = ''.join(brace_builder) name_str = '{:^{}}'.format(self.name, display_width) below = stack_str_blocks(child_strs) return name_str + 'n' + brace + 'n' + below # SNIP (your other methods)
而且我们要参加比赛了!
a +-+-+---------------------------+ b e f g + +-+-------------------------+ c h i k + + +-+-+-+-------------+-------------+-+------+ d j l m p r s O P Q + + +-+-+-+---------+ +-----+ n q t u w x y R S + + +-------+-------+ +---+---+ o v z A M T U Z +-+-+-+-+-+-+ ++ + B D E H I K L NV a + + + +-+-+ + C F J W X Y b + G
(诸如“将^置于父母以下的要求”留给读者练习)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)