I need your help on an incomplete code which I wrote to handle the issue I have.
So I have this input file :-
-----INPUT : test2.csv-----
child, parent, relation
M3,Q,P
M54,M7,P
M54,M27,E
Q,M7,P
M7,Q,E
M7,M3,P
M27,Q,E
======OUTPUT REQUIRED====
M3->Q,P
M54->M7->Q,P
M7->Q,E
M27->Q,E
==================PROBLEM EXPLANATION===================
Q is the ultimate parent. I want to trace all childs back to Q (the shortest path to parent 'Q'). For example for the first row, the output should be =
M3->Q, P
But second row, M54 is child of M7 with a relation tag of 'P' (M54->M7, P), but we need to traverse M7 to the ultimate parent who is 'Q'. As we search through along the csv file for M7's parent, we see that from row 5 & 6, M7 can have either 'M3' as his parent or 'Q' as his parent. So we have two paths tracing to the ultimate parent Q :-
M54->M7->Q,PE & M54->M7->M3->Q,PPP
But we would like to have the shortest path only , i.e.
M54->M7->Q,PE
Another issue is that we also have cyclic paths, eg consider row 4 & 5 :-
Q,M7,P
M7,Q,E
So in such a case we would like the output as M7->Q,E (rather than Q->M7->Q as one would expect).
This is the code Ive come up with so far :-
# Read the csv file
import csv
z=[]
with open('test2.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
z.append(row)
# Now generate list-of-list to store relations. Eg [['M7', 'Q', ['P']],.....
for i in range(len(z)):
t=z[i].pop()
z[i].append([t])
# Now lets populate the list
t=[]
out=[]
for i in range(len(z)):
child = z[i][0]
if z[i][1]=='Q': #whos the parent ?
out.append(z[i])
continue
t.append(z[i])
index=t.index(z[i])
print (index)
parent=t[index][1]
print (parent)
length=len(t[index])
for j in range(len(z)):
if z[j][0] == child:
if z[j][1]=='Q':
t[index].insert(length,'Q')
#print (parent)
print ("temp=",t)
print ("out=",out)