[英]Python: Printing a new line after a recursive function
I'm writing a tree traversal method. 我正在写一个遍历树的方法。 The output needs to be on one line.
输出必须在一行上。 When the method is complete, though, I'd like to insert a line break.
但是,当方法完成后,我想插入一个换行符。 Is there any way to do this within the function, or will it have to be called from outside?
在函数中有什么方法可以执行此操作,还是必须从外部调用它?
Right now I have: 现在我有:
def postorder_transversal(self):
if self.node == None:
return 0
for child in self.children:
child.postorder_transversal()
print self.node,
Any thoughts on how to alter it? 关于如何更改它的任何想法?
You could do it inside the function like so: 您可以在函数内部执行以下操作:
def postorder_transversal(self, add_newline=True):
if self.node == None:
return 0
for child in self.children:
child.postorder_transversal(add_newline=False)
print self.node,
if add_newline:
print
though it may be cleaner to just do it outside. 虽然外面做可能更清洁。
You could pass the depth as a parameter: 您可以将depth作为参数传递:
def postorder_transversal(self, depth=0):
if self.node == None:
return 0
for child in self.children:
child.postorder_transversal(depth=depth + 1)
print self.node,
if depth == 0:
print
And with the print
function: 并具有
print
功能:
from __future__ import print_function
def postorder_transversal(self, depth=0):
if self.node == None:
return 0
for child in self.children:
child.postorder_transversal(depth=depth + 1)
print(self.node, end='\n' * (depth == 0))
After this function backs out of recursion, it will print a bunch of nodes. 此函数退出递归后,它将打印一堆节点。 Right after that, add a newline to stdout.
之后,在stdout中添加换行符。 So yes, outside.
是的,外面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.