I have the following problem:
First of all, I have a list of tuples like the following:
[(1,2),(2,3),(4,5),(5,6),(5,7),(5,8),(6,9),(6,10),(7,11),(12,14)]
To make things easier let's say that the first number in each tuple 'controls' the second (for those who are familiar with dependency parsing, the first number represents the index of the head, while the second the index of the dependent).
Now what I want to create is function that takes as argument an int
and the list above. The function has to look for all the tuples that have as first number the integer argument and return the second number. The function should then recursively take each of these second number, look what are the tuples where it appears as first number and return the second number. This should go on until no other second numbers can be retrieved.
I will use an example to explain it better:
let's say that this function takes as input the number 5. The tuples having 5 as first number are (5,6),(5,7),(5,8)
; as first result the function should then take 6,7,8 and append it to a list
. Now the function should consider 6,7,8 , look for the tuples where they appear as first numbers ((6,9),(6,10),(7,11)
) and return the second numbers (9,10,11). Since 8 does not appear as first number in any of the tuples, its journey ends at this stage. The final list returned should then be [6,7,8,9,10,11]
.
I have tried something like that but it doesn't work:
def foo(start_index, lista_tuples,list_to_return=list()):
indeces=[x[1] for x in lista_tuples if x[0]==start_index]
list_to_return.extend(indeces)
for index in indeces:
foo(index,lista_tuples,list_to_return)
return list_to_return
but it doesn't work. Can someone help me?