Find intersected sub-lists on nested list using condition

Hi,

I have to “intersect” several sub-lists in a list, in order to get a result list r, result list r is obtained linking several sub-lists that contain one “intersected” and same item. The intersected item is part of a subset p. The goal is to traverse the list, starting at element “start” and ending on element “end”.

  • Result list r is build from and initial list l.
  • 1st sub-list in r must contain starting point start, and intermediate sub-lists that are interconnected by elements from list p.
  • The last sub-list in r must contain ending point end.

It is like finding the sub-lists connected by elements in ‘p’.

Here a small example.

> #starting point
> start = 1
> 
> #ending point
> end = 9
> 
>  #items to be used to link "start" and "end" points.
> p = [2, 4, 5]
> 
> #complete nested list
> l = [
>     [0, 7],
>     [1, 2],
>     [8, 15, 19, 20],
>     [0, 6],
>     [2, 3, 5],
>     [10, 14],
>     [5, 8, 3, 4],
>     [4, 9, 6],
>     [14, 21],
>     [20, 9]
> ]
> 
> #result list, with "start" in sublist 0, "end" in sublist 3.
> r = [
>     [1, 2],
> #----^
>     [2, 3, 5],
>     [5, 8, 3, 4],
>     [4, 9, 6]
> #-------^
> ]
> ```

I can find a solution only when there is needed 2 sub-lists to go from starting point to ending point. But for cases with several intermediate lists is not possible for me right now.


Thanks for your help.