How to iterate more pythonic for an event?

Here it is: mylist = range(100)and I have a discontinuous path from src=1to dest=99with an array pre[100], each value of which represents the last one elemin path. The question arises: how can I get all elemsin pathfrom destbefore src. You can do this:

    path = []
    i = dst
    while i != src:
      path.append(i)
      i = pre[i]
    path.append(src)

But is there an easier way using only one operator?

Input example

dst, src = 3, 2
pre = [2, 0, 3, 1]

Exit

[3, 1, 0, 2]   #It just have to follow the path with the indices from 3 to 2.

Explanation:

              src dst
                vv
Indices: 0 1 2 3
Pre: 2 0 3 1

From dest 3, the predecessor is 1, so we go to 1.
From node 1, the predecessor is 0, so we go to 0.
From node 0, the predecessor is 2, so we go to 2.
2 is src, so we're done.
+4
source share
3

Pythonic - , :

def gen_path(src, dst, pre):
    while dst != src:
        yield dst
        dst = pre[dst]
    yield src

, , list(gen_path(src, dst, pre)).

, ( node , ). , , 2- next lambda , .

+4

. . . . . , yield , .

: " , , . , , ".


, , , :

>>> from itertools import takewhile, accumulate, repeat
>>> dst, src = 3, 2
>>> pre = [2, 0, 3, 1]
>>> list(takewhile(lambda x: x != src, 
                   accumulate(repeat(dst), lambda x,y: pre[x]))) + [src]
[3, 1, 0, 2]

Python >= 3.3, accumulate . , reduce, , , - , .

+4

To not be outonelined @DSM

z = lambda i=dst, p=[]: p if p.append(i) or i==src else z(pre[i]); z()

Needless to say - no one should use such code

+2
source

All Articles