如何使用stdout python3摆脱尾随空白打印列表

时间:2019-02-15 22:21:51

标签: python python-3.x binary-search-tree stdout preorder

我正在使用python中的stdout打印输出,但是它保留了要打印的内容最后是空格,并且{ "configurations": [ { "environments": [ { "MINGW64_ROOT": "C:\\msys64\\mingw64", "BIN_ROOT": "${env.MINGW64_ROOT}\\bin", "FLAVOR": "x86_64-w64-mingw32", "TOOLSET_VERSION": "7.3.0", "PATH": "${env.MINGW64_ROOT}\\bin;${env.MINGW64_ROOT}\\..\\usr\\local\\bin;${env.MINGW64_ROOT}\\..\\usr\\bin;${env.MINGW64_ROOT}\\..\\bin;${env.PATH}", "INCLUDE": "${env.MINGW64_ROOT}\\include\\c++\\${env.TOOLSET_VERSION};${env.MINGW64_ROOT}\\include\\c++\\${env.TOOLSET_VERSION}\\tr1;${env.MINGW64_ROOT}\\include\\c++\\${env.TOOLSET_VERSION}\\${env.FLAVOR};${env.MINGW64_ROOT}\\include", "environment": "mingw_64" } ], "name": "Mingw64-Debug", "generator": "Ninja", "configurationType": "Debug", "inheritEnvironments": [ "mingw_64" ], "buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}", "installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}", "cmakeCommandArgs": "", "buildCommandArgs": "-v", "ctestCommandArgs": "", "intelliSenseMode": "linux-gcc-x64", "variables": [ { "name": "CMAKE_C_COMPILER", "value": "${env.BIN_ROOT}\\clang.exe" }, { "name": "CMAKE_CXX_COMPILER", "value": "${env.BIN_ROOT}\\clang++.exe" } ] } ] } 总是给我一个错误。下面的代码。

Generic iOS Device

我用输入rsplit()得到输出 class Node: def __init__(self, d): self.data = d self.left = None self.right = None # function to convert sorted array to a # balanced BST # input : sorted array of integers # output: root node of balanced BST def sort_array_to_bst(arr): if not arr: return None # find middle mid = (len(arr)) / 2 mid = int(mid) # make the middle element the root root = Node(arr[mid]) # left subtree of root has all # values <arr[mid] root.left = sort_array_to_bst(arr[:mid]) # right subtree of root has all # values >arr[mid] root.right = sort_array_to_bst(arr[mid + 1:]) return root # A utility function to print the pre-order # traversal of the BST def pre_order(node): if not node: return if root: sys.stdout.write(node.data + ' ') pre_order(node.left) pre_order(node.right) def no_spaces(s): return ' '.join(s.rsplit()) if __name__ == '__main__': arr = [] for line in sys.stdin.readline().strip().split(" "): arr.append(line) # arr = [7, 898, 157, 397, 57, 178, 26, 679] # Output = 178 57 26 157 679 397 898 narr = arr[1:] print(narr) narr = sorted(narr, key=int) root = sort_array_to_bst(narr) pre_order(root) 7 898 157 397 57 178 26 679用于说明空白,但请注意,在实际输出中,它只是空白。我尝试过
178 57 26 157 679 397 898.,但获得: `AttributeError:'int'对象没有属性'rsplit'。 我该怎么做,或者有其他选择吗?

1 个答案:

答案 0 :(得分:1)

这是在 元素之间仅打印空格的一种方法:

if root:
    if node != root:
       sys.stdout.write(' ')
    sys.stdout.write(str(node.data))
    pre_order(node.left)
    pre_order(node.right)