Find path with unsorted data

2019-08-15 19:24发布

问题:

I have this data:

data = [
    {"start": "MIA", "end": "FCA"},
    {"start": "FCA", "end": "GVK"},
    {"start": "GVK", "end": "LSD"}
]

With this data, I need to find a path. In the above case, the path would be from MIA to FCA, then FCA to GVK and, finally, GVK to LSD. The path will never have branches and It never goes back to a point that It has already passed, no loops. As output, I just need to get the "end" point of each element of the data array: ["FCA", "GVK", "LSD"]

So, that's what I've tried:

def find_path(connections, counter, data):
    if connections[-1] == data[counter]["start"]:
        connections.append(data[counter]["end"])
        if len(connections) == len(data):
            return connections
    return find_path(connections, counter+1, data)

It works only because the data is sorted. But when I change data just like this:

data = [
    {"start": "FCA", "end": "GVK"},
    {"start": "MIA", "end": "FCA"},
    {"start": "GVK", "end": "LSD"}
]

It fails.

QUESTION: What would be a neat way to achieve this?

I thought about resetting the counter in the top of the function when it reaches the end of the data: counter = 0 if counter == len(data) else counter, but with this, I would have to discount at connections index here: if connections[-1] == data[counter]["start"]: and append data element in a different position here: connections.append(data[counter]["end"]). I think It's getting a little bit messy.

回答1:

The following recursive function will do the job:

data = [
    {"start": "FCA", "end": "GVK"},
    {"start": "MIA", "end": "FCA"},
    {"start": "GVK", "end": "LSD"}
]

def find_path(data, start='', result=[]):
    l = data.copy()
    for d in data:
        if d['start'] == start:
            result.append(d['end'])
            l.remove(d)
            find_path(l, result[-1], result)
    return result

print(find_path(data, 'MIA'))

The output:

['FCA', 'GVK', 'LSD']