human
Check if two nodes are on same path in a tree | Set 2 | Function to filter the return Values.
Utility function to check if nodes are on same path or not.
Condition to check if any vertex is equal to given two vertex or not.
Check if the current position has 1.
Recursive call.
Return LCA.
Function to check if nodes lies on same path or not.
Driver code"
How can the above be solved in Python?
assistant
#Here is code to check if two nodes are on same path in a tree and the other steps required.
 def filter ( x , y , z ) :
	if ( x != - 1 and y != - 1 ) :
		return z
	return y if x == - 1 else x
def samePathUtil ( mtrx , vrtx , v1 , v2 , i ) :
	ans = - 1
	if ( i == v1 or i == v2 ) :
		return i
	for j in range ( 0 , vrtx ) :
		if ( mtrx [ i ] [ j ] == 1 ) :
			ans = filter ( ans , samePathUtil ( mtrx , vrtx , v1 , v2 , j ) , i )
	return ans
def isVertexAtSamePath ( mtrx , vrtx , v1 , v2 , i ) :
	lca = samePathUtil ( mtrx , vrtx , v1 - 1 , v2 - 1 , i )
	if ( lca == v1 - 1 or lca == v2 - 1 ) :
		return True
	return False
vrtx = 7
edge = 6
mtrx = [ [ 0 , 1 , 1 , 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ]
v1 = 1
v2 = 5
if ( isVertexAtSamePath ( mtrx , vrtx , v1 , v2 , 0 ) ) :
	print ( " Yes " )
else :
	print ( " No " )