Skip to content

Instantly share code, notes, and snippets.

@souenzzo
Last active March 3, 2018 02:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save souenzzo/58dbf654da3e6beebb6264e08970c457 to your computer and use it in GitHub Desktop.
Save souenzzo/58dbf654da3e6beebb6264e08970c457 to your computer and use it in GitHub Desktop.
#!/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