Last active
March 3, 2018 02:55
-
-
Save souenzzo/58dbf654da3e6beebb6264e08970c457 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from functools import reduce | |
def append_to_graph(graph, elms): | |
if len(elms) == 0: | |
return graph | |
el, *ms = elms | |
if type(el) is str: | |
return append_to_graph({**graph, **{el: set()}}, ms) | |
e, l = el | |
return append_to_graph({**graph, **{e: graph[e] | {l}, | |
l: graph[l] | {e}}}, | |
ms) | |
def make_graph (*args): | |
return append_to_graph({}, args) | |
def find_paths(graph, src, dest, path=[]): | |
path = path + [src] | |
if src == dest: | |
return [path] | |
if src not in graph: | |
return [] | |
## Sintaxe tosca do python não deixa eu quebrar linha ai fica essa merda longa | |
return reduce(lambda p, edge: [*p, *find_paths(graph, edge, dest, path)] if edge not in path else p, | |
graph[src], | |
[]) | |
graph = make_graph("a", "b", "c", "d", "e", | |
## ^ nós (pessoas) | |
## \/ relações (amizades) | |
{"a", "b"}, | |
{"b", "c"}, | |
{"b", "d"}, | |
{"c", "d"}, | |
{"a", "d"}, | |
{"d", "e"}) | |
menor, *outros = sorted(find_paths(graph, "a", "e"), | |
key=lambda x: len(x)) | |
print({"menor": menor, "outros": outros}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment