+ 1

here in the below code bit at line 11,i amconfusing at p=self.parent ,but here self is root,as root parent is none

in the code bit in line 11 it is showing that p=self.parent but self here is root and root will not have parent so it is null.but the code is working in finding level. please explain the code

15th Nov 2023, 9:11 AM
CHENNAMSETTY SUMANTH
CHENNAMSETTY SUMANTH - avatar
4 ответов
+ 1
class TreeNode: def __init__(self,data): self.data = data self.children = [] self. parent = None def add_child(self,child): child.parent = self self.children.append(child) def get_level(self): level = 0 p = self.parent while p : p = p.parent level += 1 return level def print_tree(self): print(' '*self.get_level() + '|--', end = '') print(self.data) if self.children: for each in self.children: each.print_tree() def run(): root = TreeNode('Eletronics') laptop = TreeNode('Laptop') root.add_child(laptop) root.print_tree() run()
15th Nov 2023, 9:14 AM
CHENNAMSETTY SUMANTH
CHENNAMSETTY SUMANTH - avatar
+ 1
CHENNAMSETTY SUMANTH , Insert a print statement, and you'll see. def get_level(self): level = 0 p = self.parent while p : p = p.parent level += 1 print(f"p {p}, level {level}") # testing return level Or use this playground to step through the code and see all variables change. https://pythontutor.com/JUMP_LINK__&&__python__&&__JUMP_LINK-compiler.html#mode=edit Paste your code in the bottom window. Click Visualize Execution. Click Next >. Click Next >. etc.
15th Nov 2023, 7:38 PM
Rain
Rain - avatar
0
CHENNAMSETTY SUMANTH , I say it's working as expected. When self is root, p == None, (you can verify it with print(p)), while p: evaluates False, get_level returns 0, and ' ' is printed 0 times. None isn't really the same as null. None is a singleton object that can be passed around that is used to represent the absence of a value, even though it's a thing. The truthiness of None is falsish when used in a condition, so it does what you want. while None: pass # never executes https://docs.python.org/3/c-api/none.html#the-none-object https://docs.python.org/3/reference/datamodel.html#none
15th Nov 2023, 12:10 PM
Rain
Rain - avatar
0
Bro..it is exciting and p=p.patent also still working
15th Nov 2023, 12:26 PM
CHENNAMSETTY SUMANTH
CHENNAMSETTY SUMANTH - avatar