-1

I understand slice notation. But need some help here.

Below code traverses and prints a binary tree. Can somebody explain what self.preorder_print(self.root, "")[:-1] line is doing here inside the print_tree function?

class Node(object):
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BinaryTree(object):
    def __init__(self, root):
        self.root = Node(root)

    def search(self, find_val):
        return self.preorder_search(self.root, find_val)

    def print_tree(self):
        return self.preorder_print(self.root, "")[:-1]

    def preorder_search(self, start, find_val):
        if start:
            if start.value == find_val:
                return True
            else:
                return self.preorder_search(start.left, find_val) or self.preorder_search(start.right, find_val)
        return False

    def preorder_print(self, start, traversal):
        if start:
            traversal += ("-" + str(start.value))
            traversal = self.preorder_print(start.left, traversal)
            traversal = self.preorder_print(start.right, traversal)
        return traversal
Harry
  • 521
  • 7
  • 21
  • Please format your question properly. Possibly highglight the problematic part in its own block too. – Markus Meskanen Aug 03 '17 at 20:35
  • This is a binary tree code. Preorder_print() funtion has to print the tree in a pre-order way. I did not understand the line "return self.preorder_print(self.root, "")[:-1]" – Harry Aug 03 '17 at 20:41
  • Possible duplicate of [Understanding Python's slice notation](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation) – Patrick Haugh Dec 18 '18 at 20:14

1 Answers1

1

the [:-1] is a slice notation, it allow to take a subsection of those object that implement it, the use is as follow [start:end:step] start is the initial position you want to start taking elements, likewise end is where to stop, if negative it would count that many position from the end, useful if you don't know how long is the object, step allow to skip elements if different than one and/or take it in reverse if negative, each one can be omitted, in which case they take appropriates default values

for example

>>> "123"[:-1]
'12'
>>> 

is to remove the last element, so in your case as preorder_print return a string, with the [:-1] it remove the last character

here you can find more about slice notation

Copperfield
  • 8,131
  • 3
  • 23
  • 29