Kevin
Kevin

Reputation: 1087

Swapping variables in a class without using a temporary variable

This is the code. It's a standard Binary Tree class.

class BinaryTree:
    def __init__(self,rootObj):
        self.key = rootObj
        self.leftChild = None
        self.rightChild = None

    def insertLeft(self,newNode):
        if self.leftChild == None:
            self.leftChild = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.leftChild = self.leftChild
            self.leftChild = t

In the else clause, could I remove the t variable and simply do this:

BinaryTree(newNode).leftChild, self.leftChild = self.leftChild, BinaryTree(newNode)

Would this work? It looks like I'm calling the BinaryTree class twice, would that create two different instances?

Upvotes: 1

Views: 104

Answers (2)

Reinier Hernández
Reinier Hernández

Reputation: 428

In a BinaryTree you must create a temporary variable, because use Object. if are a integer could be:

a = 5
b = 3
a += b # a = 8
b = a - b # b = 5
a -= b # a = 3
print(a)
>>3
print(b)
>>5

Upvotes: 0

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

No unfortunately you need to be able to keep track of the newly created BinaryTree instance and the previous self.leftChild value at the same time as you have it written, using simultaneous assignments will not work in this scenario.

However if you allowed the leftChild to be specified in the constructor then the new BinaryTree instance could be created with self.leftChild right away:

class BinaryTree:
    def __init__(self,rootObj, leftnode=None, rightnode=None):
        self.key = rootObj
        self.leftChild = leftnode
        self.rightChild = rightnode

    def insertLeft(self,newNode):
        #if self.leftChild == None: pass leftnode=None to constructor.
        # which is the same as passing leftnode=self.leftChild
        self.leftChild = BinaryTree(newNode, leftnode = self.leftChild)

This way the newly created node has its own leftChild attribute set upon initialization so there is no need to manually do it in insertLeft.

Upvotes: 1

Related Questions