[Python] Using self.xxxx as a default parameter for recursive function - Python

Discussão em 'Python' iniciado por Stack, Junho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to simplify my work and fine-tune the code. What I'm working with is a binary search tree. Right now I have a function in my Tree() class that finds all the elements and puts them into a list.

    tree = Tree()
    #insert a bunch of items into tree


    then I use my makeList() function to take all the nodes from the tree and puts them in a list. To call the makeList() function, I do tree.makeList(tree.root). To me this seems a little repetitive. I'm already calling the tree object with tree.so the tree.root is just a waste of a little typing.

    Right now the makeList function is:

    def makeList(self, aNode):
    if aNode is None:
    return []
    return [aNode.data] + self.makeList(aNode.lChild) + self.makeList(aNode.rChild)


    I would like to make the aNode input a default parameter such as aNode = self.root (which does not work) that way I could run the function with this, tree.makeList().

    First question: why doesn't that work?
    Second question: is there a way that it can work (for this kind of recursive function)? As you can see the makeList() function is recursive so I cannot unconditionally initialize as any constant value at the beginning of the function or else I get an infinite loop.

    EDIT Here is all the code as requested:

    class Node(object):
    def __init__(self, data):
    self.data = data
    self.lChild = None
    self.rChild = None

    class Tree(object):
    def __init__(self):
    self.root = None

    def __str__(self):
    current = self.root

    def isEmpty(self):
    if self.root == None:
    return True
    else:
    return False

    def insert (self, item):
    newNode = Node (item)
    current = self.root
    parent = self.root

    if self.root == None:
    self.root = newNode
    else:
    while current != None:
    parent = current
    if item < current.data:
    current = current.lChild
    else:
    current = current.rChild

    if item < parent.data:
    parent.lChild = newNode
    else:
    parent.rChild = newNode

    def inOrder(self, aNode):
    if aNode != None:
    self.inOrder(aNode.lChild)
    print aNode.data
    self.inOrder(aNode.rChild)

    def makeList(self, aNode):
    if aNode is None:
    return []
    return [aNode.data] + self.makeList(aNode.lChild) + self.makeList(aNode.rChild)


    def isSimilar(self, n, m):
    nList = self.makeList(n.root)
    mList = self.makeList(m.root)
    print mList == nList

    Continue reading...

Compartilhe esta Página