Search code examples
pythonpython-3.xbinary-search-treestdoutpreorder

How to get rid of trailing whitespace printing a list using stdout python3


I'm printing an output using stdout in python, but it keeps the things it keeps printing has whitespace at the end, and rsplit() always gives me an error. Code Below.



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)

I with the input 7 898 157 397 57 178 26 679 I get the output 178 57 26 157 679 397 898. The . is to illustrate the whitespace, but note in the actual output it is just a blank space. I've tried to
sys.stdout.write(node.data + ' ').rsplit() but get the: `AttributeError: 'int' object has no attribute 'rsplit'. How can I do this, or are there any alternatives?


Solution

  • Here is one way to print a space only between elements:

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