使用stdout在同一行上打印列表

时间:2019-02-15 15:56:45

标签: python list binary-tree stdout sys

我正在尝试使用stdout而不是print获得BST的输出。问题是当stdout显示值时似乎变得混乱了。

我尝试做诸如sys.stdout.write(' '.join(str(x) for x in str(node.data)))之类的事情。还有sys.stdout.write(str(node.data))。下面的代码。

import sys


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 preorder
# traversal of the BST
def pre_order(node):
    if not node:
        return

    #sys.stdout.write(' '.join(str(x) for x in str(node.data)))
    # Output : 5 71 5 78 9 83 9 72 61 7 86 7 9
    #sys.stdout.write(str(node.data))
    # Output: 5715789839726178679
    #print(node.data, end=" ")
    pre_order(node.left)
    pre_order(node.right)


arr = [7, 898, 157, 397, 57, 178, 26, 679]
root = sort_array_to_bst(arr[1:])
pre_order(root)

预计输出为57 157 898 397 26 178 679

但是正如sys.stdout.write(' '.join(str(x) for x in str(node.data)))的代码中注释的那样,我得到了输出5 71 5 78 9 83 9 72 61 7 86 7 9

对于sys.stdout.write(str(node.data)),我得到输出5715789839726178679

反正有实现这一目标的方法吗?

2 个答案:

答案 0 :(得分:1)

您正在' '.join()上调用str(node.data),这意味着它将花费57并在57的每个字符之间加入一个空格。只需在sys.stdout.write(str(node.data) + ' ')函数中用pre_order()替换标准输出即可。

答案 1 :(得分:0)

在遍历node.data之前,不应将其转换为字符串。否则,您将遍历字符串的各个字符。

更改:

sys.stdout.write(' '.join(str(x) for x in str(node.data)))

收件人:

sys.stdout.write(' '.join(str(x) for x in node.data))
相关问题