无法弄清楚如何从我的结果中删除尾随空格
Can't work out how to remove the trailing whitespace from my result
我的代码从数组中找到平衡二叉树的输入。
array = [178, 57, 26, 157, 679, 397, 898]
def myFunc(x):
for i in range(1, len(x)):
inp = x[i]
j=i-1
while j>=0 and inp<x[j]:
x[j+1] = x[j]
j-=1
x[j+1] = inp
x
class tn(object):
def __init__(self, y):
self.val = y
self.left = None
self.right =None
def sort2bst(x):
if not x:
return None
m = len(x)//2
node = tn(x[m])
node.left = sort2bst(x[:m])
node.right = sort2bst(x[m+1:])
return node
def po(node):
if not node:
return
print(node.val, end=" ")
po(node.left)
po(node.right)
result = sort2bst(x)
po(result)
myFunc(array)
输出如下所示:178 57 26 157 679 397 898
到目前为止,除了从输出中删除结尾的白色 space 之外,我已经能够完成所有操作。我必须使用 end=" "
才能在一行中输出,但这意味着最后一个值后面还有一个空的 space。我尝试使用 .rstrip()
但这也不起作用,因为我认为它只适用于字符串。我怎么去掉最后这个白色的space?
您可以收集结果并在获得所有结果后创建字符串,而不是连续打印:
def po(node):
if not node:
return []
return [str(node.val), *po(node.left), *po(node.right)]
result = sort2bst(x)
print(" ".join(po(result)))
我的代码从数组中找到平衡二叉树的输入。
array = [178, 57, 26, 157, 679, 397, 898]
def myFunc(x):
for i in range(1, len(x)):
inp = x[i]
j=i-1
while j>=0 and inp<x[j]:
x[j+1] = x[j]
j-=1
x[j+1] = inp
x
class tn(object):
def __init__(self, y):
self.val = y
self.left = None
self.right =None
def sort2bst(x):
if not x:
return None
m = len(x)//2
node = tn(x[m])
node.left = sort2bst(x[:m])
node.right = sort2bst(x[m+1:])
return node
def po(node):
if not node:
return
print(node.val, end=" ")
po(node.left)
po(node.right)
result = sort2bst(x)
po(result)
myFunc(array)
输出如下所示:178 57 26 157 679 397 898
到目前为止,除了从输出中删除结尾的白色 space 之外,我已经能够完成所有操作。我必须使用 end=" "
才能在一行中输出,但这意味着最后一个值后面还有一个空的 space。我尝试使用 .rstrip()
但这也不起作用,因为我认为它只适用于字符串。我怎么去掉最后这个白色的space?
您可以收集结果并在获得所有结果后创建字符串,而不是连续打印:
def po(node):
if not node:
return []
return [str(node.val), *po(node.left), *po(node.right)]
result = sort2bst(x)
print(" ".join(po(result)))