I'm doing a programming assignment for my class. One of my programs includes creating a BST with Python within a BST class, and I'm trying to display using preorder() and inorder() functions. My professor gave us certain parameters for the assignment, so I've had to code in constraints, but I am struggling with the implementation. I'm not allowed to use self in preorder() and inorder() based on given parameters, nor am I allowed to insert parameters for display(). I want to use the f/function in preorder() and inorder()to call print inside my display() method when calling the functions. X is the value of the root inside the lambda function. However, I know there's a gap in my understanding based on my logic and the problems I'm encountering.
For reference, here is a snippet of my code.
def inorder(f):
return tree.inorderHelper(root, f)
def inorderHelper(root, f):
if root:
tree.inorderHelper(root.left, f)
f(root.x)
tree.inorderHelper(root.right, f)
def preorder(f):
return tree.preorderHelper(root, f)
def preorderHelper(root, f):
if root:
f(root.x)
tree.preorderHelper(root.left, f)
tree.preorderHelper(root.right, f)
@staticmethod
def display():
if random.randint(0,1) == 0:
tree.preorder(lambda x: print(x, end=" "))
elif random.randint(0,1) == 1:
tree.inorder(lambda x: print(x, end=" "))
if __name__ == "__main__":
print("Hello world!")
tree = tree()
root = None
for i in range(4):
print(i)
tree.ins(i)
tree.display()
print("Testing preorder")
I've tried creating a printInorder(root) or printPreorder(root) traversal method with similar logic instead of preorder() and inorder() directly, but I always get an error saying that I'm having issues with using too many arguments. I also tried using lambda directly, but I know that's not correct either; I'm getting the same error with arguments. Any help would be appreciated.
@staticmethodcan only be used in a class, but there is none. What is thetreeclass? Alsoselfis just a name. An instruction to not useselfis useless, as it is just whatever you name the first parameter. So if you call itthisorthatortree, ... its all the same purpose.randintgood for? What if neither theif, nor theelifcondition is true? Are you really using a method that accessestreeas a global variable? If that is what your teacher told you to do, I would strongly advise to look for a different course. That's bad practice.if __name__ == "__main__", and see what turns red. Ideally, no function in this script would rely on the global scope... but depending on how literal "... nor am I allowed to insert parameters for display() ..." is, you may be forced to