Find path with unsorted data

北城以北 提交于 2019-12-11 04:39:45

问题


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']


来源:https://stackoverflow.com/questions/46037228/find-path-with-unsorted-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!