Count the nodes in the given Tree whose weight is a Perfect Number | Python3 implementation to Count the Nodes in the given tree whose weight is a Perfect Number ; Function that returns True if n is perfect ; Variable to store sum of divisors ; Find all divisors and add them ; Check if sum of divisors is equal to n , then n is a perfect number ; Function to perform dfs ; If weight of the current Node is a perfect number ; Weights of the Node ; Edges of the tree
graph = [ [ ] for i in range ( 100 ) ] NEW_LINE weight = [ 0 ] * 100 NEW_LINE ans = 0 NEW_LINE def isPerfect ( n ) : NEW_LINE INDENT sum = 1 ; NEW_LINE i = 2 ; NEW_LINE while ( i * i < n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i * i != n ) : NEW_LINE INDENT sum = sum + i + n / i ; NEW_LINE DEDENT else : NEW_LINE INDENT sum = sum + i ; NEW_LINE DEDENT DEDENT i += 1 ; NEW_LINE DEDENT if ( sum == n and n != 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def dfs ( Node , parent ) : NEW_LINE INDENT global ans ; NEW_LINE if ( isPerfect ( weight [ Node ] ) ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT for to in graph [ Node ] : NEW_LINE INDENT if ( to == parent ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT dfs ( to , Node ) ; NEW_LINE DEDENT DEDENT weight [ 1 ] = 5 ; NEW_LINE weight [ 2 ] = 10 ; NEW_LINE weight [ 3 ] = 11 ; NEW_LINE weight [ 4 ] = 8 ; NEW_LINE weight [ 5 ] = 6 ; NEW_LINE graph [ 1 ] . append ( 2 ) ; NEW_LINE graph [ 2 ] . append ( 3 ) ; NEW_LINE graph [ 2 ] . append ( 4 ) ; NEW_LINE graph [ 1 ] . append ( 5 ) ; NEW_LINE dfs ( 1 , 1 ) ; NEW_LINE print ( ans ) ; NEW_LINE